mirror of
https://github.com/nushell/nushell.git
synced 2025-08-20 03:59:04 +02:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f11be69ed | ||
|
|
69765340f3 | ||
|
|
4be392fcb4 | ||
|
|
81531e224e | ||
|
|
370639d7d7 | ||
|
|
d326f6def6 |
@@ -12,22 +12,3 @@ rustflags = ["-C", "link-args=-stack:10000000", "-C", "target-feature=+crt-stati
|
|||||||
# set a 2 gb stack size (0x80000000 = 2147483648 bytes = 2 GB)
|
# set a 2 gb stack size (0x80000000 = 2147483648 bytes = 2 GB)
|
||||||
# [target.x86_64-apple-darwin]
|
# [target.x86_64-apple-darwin]
|
||||||
# rustflags = ["-C", "link-args=-Wl,-stack_size,0x80000000"]
|
# rustflags = ["-C", "link-args=-Wl,-stack_size,0x80000000"]
|
||||||
|
|
||||||
# How to use mold in linux and mac
|
|
||||||
|
|
||||||
# [target.x86_64-unknown-linux-gnu]
|
|
||||||
# linker = "clang"
|
|
||||||
# rustflags = ["-C", "link-arg=-fuse-ld=/usr/local/bin/mold"]
|
|
||||||
|
|
||||||
# [target.x86_64-apple-darwin]
|
|
||||||
# linker = "clang"
|
|
||||||
# rustflags = ["-C", "link-arg=-fuse-ld=mold"]
|
|
||||||
|
|
||||||
# [target.aarch64-apple-darwin]
|
|
||||||
# linker = "clang"
|
|
||||||
# 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
2
.gitattributes
vendored
@@ -1,2 +0,0 @@
|
|||||||
# Example of a `.gitattributes` file which reclassifies `.nu` files as Nushell:
|
|
||||||
*.nu linguist-language=Nushell
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
#!/usr/bin/env nu
|
|
||||||
|
|
||||||
use ../toolkit.nu fmt
|
|
||||||
|
|
||||||
fmt --check --verbose
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
#!/usr/bin/env nu
|
|
||||||
|
|
||||||
use ../toolkit.nu [fmt, clippy]
|
|
||||||
|
|
||||||
fmt --check --verbose
|
|
||||||
clippy --verbose
|
|
||||||
1
.github/AUTO_ISSUE_TEMPLATE/README.md
vendored
1
.github/AUTO_ISSUE_TEMPLATE/README.md
vendored
@@ -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.
|
|
||||||
@@ -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: [](https://github.com/nushell/nushell/actions/workflows/nightly-build.yml)
|
|
||||||
19
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
19
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -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:
|
||||||
@@ -47,4 +53,11 @@ body:
|
|||||||
| features | clipboard-cli, ctrlc, dataframe, default, rustyline, term, trash, uuid, which, zip |
|
| features | clipboard-cli, ctrlc, dataframe, default, rustyline, term, trash, uuid, which, zip |
|
||||||
| 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: false
|
||||||
|
- type: textarea
|
||||||
|
id: context
|
||||||
|
attributes:
|
||||||
|
label: Additional context
|
||||||
|
description: Add any other context about the problem here.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
|||||||
1
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
1
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@@ -1,6 +1,5 @@
|
|||||||
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"]
|
|
||||||
body:
|
body:
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: problem
|
id: problem
|
||||||
|
|||||||
21
.github/ISSUE_TEMPLATE/question.yml
vendored
21
.github/ISSUE_TEMPLATE/question.yml
vendored
@@ -1,21 +0,0 @@
|
|||||||
name: Question
|
|
||||||
description: "When you have a question to ask"
|
|
||||||
labels: "question"
|
|
||||||
body:
|
|
||||||
- type: textarea
|
|
||||||
id: problem
|
|
||||||
attributes:
|
|
||||||
label: Question
|
|
||||||
description: Leave your question here
|
|
||||||
placeholder: |
|
|
||||||
A clear and concise question
|
|
||||||
Example: Is there any equivalent of bash's $CDPATH in Nu?
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: context
|
|
||||||
attributes:
|
|
||||||
label: Additional context and details
|
|
||||||
description: Add any other context, screenshots or other media that will help us understand your question here, if needed.
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
40
.github/dependabot.yml
vendored
40
.github/dependabot.yml
vendored
@@ -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"
|
|
||||||
40
.github/labeler.yml
vendored
40
.github/labeler.yml
vendored
@@ -1,40 +0,0 @@
|
|||||||
# A bot for automatically labelling pull requests
|
|
||||||
# See https://github.com/actions/labeler
|
|
||||||
|
|
||||||
dataframe:
|
|
||||||
- changed-files:
|
|
||||||
- any-glob-to-any-file:
|
|
||||||
- crates/nu_plugin_polars/**
|
|
||||||
|
|
||||||
std-library:
|
|
||||||
- changed-files:
|
|
||||||
- any-glob-to-any-file:
|
|
||||||
- crates/nu-std/**
|
|
||||||
|
|
||||||
ci:
|
|
||||||
- changed-files:
|
|
||||||
- any-glob-to-any-file:
|
|
||||||
- .github/workflows/**
|
|
||||||
|
|
||||||
|
|
||||||
LSP:
|
|
||||||
- changed-files:
|
|
||||||
- any-glob-to-any-file:
|
|
||||||
- crates/nu-lsp/**
|
|
||||||
|
|
||||||
parser:
|
|
||||||
- changed-files:
|
|
||||||
- any-glob-to-any-file:
|
|
||||||
- crates/nu-parser/**
|
|
||||||
|
|
||||||
pr:plugins:
|
|
||||||
- changed-files:
|
|
||||||
- any-glob-to-any-file:
|
|
||||||
# plugins API
|
|
||||||
- crates/nu-plugin/**
|
|
||||||
- crates/nu-plugin-core/**
|
|
||||||
- crates/nu-plugin-engine/**
|
|
||||||
- crates/nu-plugin-protocol/**
|
|
||||||
- crates/nu-plugin-test-support/**
|
|
||||||
# specific plugins (like polars)
|
|
||||||
- crates/nu_plugin_*/**
|
|
||||||
43
.github/pull_request_template.md
vendored
43
.github/pull_request_template.md
vendored
@@ -1,40 +1,17 @@
|
|||||||
<!--
|
|
||||||
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.
|
(description of your pull request here)
|
||||||
-->
|
|
||||||
|
|
||||||
# User-Facing Changes
|
# Tests
|
||||||
<!-- List of all changes that impact the user experience here. This helps us keep track of breaking changes. -->
|
|
||||||
|
|
||||||
# Tests + Formatting
|
Make sure you've done the following:
|
||||||
<!--
|
|
||||||
Don't forget to add tests that cover your changes.
|
- [ ] Add tests that cover your changes, either in the command examples, the crate/tests folder, or in the /tests folder.
|
||||||
|
- [ ] Try to think about corner cases and various ways how your changes could break. Cover them with tests.
|
||||||
|
- [ ] If adding tests is not possible, please document in the PR body a minimal example with steps on how to reproduce so one can verify your change works.
|
||||||
|
|
||||||
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 --features=extra -- -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 --features=extra` to check that all the 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
|
|
||||||
<!-- 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. -->
|
|
||||||
|
|||||||
25
.github/workflows/audit.yml
vendored
25
.github/workflows/audit.yml
vendored
@@ -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 }}
|
|
||||||
52
.github/workflows/beta-test.yml
vendored
52
.github/workflows/beta-test.yml
vendored
@@ -1,52 +0,0 @@
|
|||||||
name: Test on Beta Toolchain
|
|
||||||
# This workflow is made to run our tests on the beta toolchain to validate that
|
|
||||||
# the beta toolchain works.
|
|
||||||
# We do not intend to test here that we are working correctly but rather that
|
|
||||||
# the beta toolchain works correctly.
|
|
||||||
# The ci.yml handles our actual testing with our guarantees.
|
|
||||||
|
|
||||||
on:
|
|
||||||
schedule:
|
|
||||||
# If this workflow fails, GitHub notifications will go to the last person
|
|
||||||
# who edited this line.
|
|
||||||
# See: https://docs.github.com/en/actions/monitoring-and-troubleshooting-workflows/monitoring-workflows/notifications-for-workflow-runs
|
|
||||||
- cron: '0 0 * * *' # Runs daily at midnight UTC
|
|
||||||
|
|
||||||
env:
|
|
||||||
NUSHELL_CARGO_PROFILE: ci
|
|
||||||
NU_LOG_LEVEL: DEBUG
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-and-test:
|
|
||||||
# this job is more for testing the beta toolchain and not our tests, so if
|
|
||||||
# this fails but the tests of the regular ci pass, then this is fine
|
|
||||||
continue-on-error: true
|
|
||||||
|
|
||||||
strategy:
|
|
||||||
fail-fast: true
|
|
||||||
matrix:
|
|
||||||
platform: [windows-latest, macos-latest, ubuntu-22.04]
|
|
||||||
|
|
||||||
runs-on: ${{ matrix.platform }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- run: rustup update beta
|
|
||||||
|
|
||||||
- name: Tests
|
|
||||||
run: cargo +beta test --workspace --profile ci --exclude nu_plugin_*
|
|
||||||
- name: Check for clean repo
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
if [ -n "$(git status --porcelain)" ]; then
|
|
||||||
echo "there are changes";
|
|
||||||
git status --porcelain
|
|
||||||
exit 1
|
|
||||||
else
|
|
||||||
echo "no changes in working directory";
|
|
||||||
fi
|
|
||||||
12
.github/workflows/check-msrv.nu
vendored
12
.github/workflows/check-msrv.nu
vendored
@@ -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
|
|
||||||
}
|
|
||||||
256
.github/workflows/ci.yml
vendored
256
.github/workflows/ci.yml
vendored
@@ -1,212 +1,180 @@
|
|||||||
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
|
||||||
- 'patch-release-*'
|
|
||||||
|
|
||||||
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 22.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 22.04 is closer to EOL (June 2027)
|
- 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-22.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@v2
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
- name: Setup Rust toolchain
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
profile: minimal
|
||||||
|
toolchain: ${{ matrix.rust }}
|
||||||
|
override: true
|
||||||
|
components: rustfmt, clippy
|
||||||
|
|
||||||
- name: cargo fmt
|
- uses: Swatinem/rust-cache@v1
|
||||||
run: cargo fmt --all -- --check
|
with:
|
||||||
|
key: "v2" # increment this to bust the cache if needed
|
||||||
|
|
||||||
|
- name: Rustfmt
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
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
|
||||||
|
with:
|
||||||
|
command: clippy
|
||||||
|
args: --features=extra --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-22.04]
|
platform: [windows-latest, macos-latest, ubuntu-latest]
|
||||||
|
style: [extra, default]
|
||||||
|
rust:
|
||||||
|
- stable
|
||||||
|
include:
|
||||||
|
- style: extra
|
||||||
|
flags: "--features=extra"
|
||||||
|
- style: default
|
||||||
|
flags: ""
|
||||||
|
exclude:
|
||||||
|
- platform: windows-latest
|
||||||
|
style: default
|
||||||
|
- platform: macos-latest
|
||||||
|
style: default
|
||||||
|
|
||||||
runs-on: ${{ matrix.platform }}
|
runs-on: ${{ matrix.platform }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4.1.7
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
- name: Setup Rust toolchain
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
profile: minimal
|
||||||
|
toolchain: ${{ matrix.rust }}
|
||||||
|
override: true
|
||||||
|
|
||||||
|
# Temporarily disabled; the cache was getting huge (2.6GB compressed) on Windows and causing issues.
|
||||||
|
# TODO: investigate why the cache was so big
|
||||||
|
# - uses: Swatinem/rust-cache@v1
|
||||||
|
# with:
|
||||||
|
# key: ${{ matrix.style }}v3 # increment this to bust the cache if needed
|
||||||
|
|
||||||
- name: Tests
|
- name: Tests
|
||||||
run: cargo test --workspace --profile ci --exclude nu_plugin_*
|
uses: actions-rs/cargo@v1
|
||||||
- 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-22.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@v2
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
- name: Setup Rust toolchain
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
profile: minimal
|
||||||
|
toolchain: ${{ matrix.rust }}
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- uses: Swatinem/rust-cache@v1
|
||||||
|
with:
|
||||||
|
key: "2" # increment this to bust the cache if needed
|
||||||
|
|
||||||
- name: Install Nushell
|
- name: Install Nushell
|
||||||
run: cargo install --path . --locked --force
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
- name: Standard library tests
|
command: install
|
||||||
run: nu -c 'use crates/nu-std/testing.nu; testing run-tests --path crates/nu-std'
|
args: --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@v2
|
||||||
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-22.04]
|
|
||||||
|
|
||||||
runs-on: ${{ matrix.platform }}
|
runs-on: ${{ matrix.platform }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4.1.7
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
- name: Setup Rust toolchain
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
profile: minimal
|
||||||
|
toolchain: ${{ matrix.rust }}
|
||||||
|
override: true
|
||||||
|
|
||||||
- name: Clippy
|
- name: Clippy
|
||||||
run: cargo clippy --package nu_plugin_* -- $CLIPPY_OPTIONS
|
uses: actions-rs/cargo@v1
|
||||||
|
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
|
||||||
|
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
|
|
||||||
|
|
||||||
wasm:
|
|
||||||
env:
|
|
||||||
WASM_OPTIONS: --no-default-features --target wasm32-unknown-unknown
|
|
||||||
CLIPPY_CONF_DIR: ${{ github.workspace }}/clippy/wasm/
|
|
||||||
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
job:
|
|
||||||
- name: Build WASM
|
|
||||||
command: cargo build
|
|
||||||
args:
|
|
||||||
- name: Clippy WASM
|
|
||||||
command: cargo clippy
|
|
||||||
args: -- $CLIPPY_OPTIONS
|
|
||||||
|
|
||||||
name: ${{ matrix.job.name }}
|
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4.1.7
|
|
||||||
|
|
||||||
- name: Setup Rust toolchain and cache
|
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
|
|
||||||
|
|
||||||
- name: Add wasm32-unknown-unknown target
|
|
||||||
run: rustup target add wasm32-unknown-unknown
|
|
||||||
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-cmd-base $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-cmd-extra $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-cmd-lang $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-color-config $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-command $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-derive-value $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-engine $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-glob $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-json $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-parser $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-path $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-pretty-hex $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-protocol $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-std $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-system $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-table $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-term-grid $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nu-utils $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
- run: ${{ matrix.job.command }} -p nuon $WASM_OPTIONS ${{ matrix.job.args }}
|
|
||||||
|
|||||||
25
.github/workflows/friendly-config-reminder.yml
vendored
25
.github/workflows/friendly-config-reminder.yml
vendored
@@ -1,25 +0,0 @@
|
|||||||
name: Comment on changes to the config
|
|
||||||
on:
|
|
||||||
pull_request_target:
|
|
||||||
paths:
|
|
||||||
- 'crates/nu-protocol/src/config/**'
|
|
||||||
jobs:
|
|
||||||
comment:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check if there is already a bot comment
|
|
||||||
uses: peter-evans/find-comment@v3
|
|
||||||
id: fc
|
|
||||||
with:
|
|
||||||
issue-number: ${{ github.event.pull_request.number }}
|
|
||||||
comment-author: 'github-actions[bot]'
|
|
||||||
body-includes: Hey, just a bot checking in!
|
|
||||||
- name: Create comment if there is not
|
|
||||||
if: steps.fc.outputs.comment-id == ''
|
|
||||||
uses: peter-evans/create-or-update-comment@v4
|
|
||||||
with:
|
|
||||||
issue-number: ${{ github.event.pull_request.number }}
|
|
||||||
body: |
|
|
||||||
Hey, just a bot checking in! You edited files related to the configuration.
|
|
||||||
If you changed any of the default values or added a new config option, don't forget to update the [`doc_config.nu`](https://github.com/nushell/nushell/blob/main/crates/nu-utils/src/default_files/doc_config.nu) which documents the options for our users including the defaults provided by the Rust implementation.
|
|
||||||
If you didn't make a change here, you can just ignore me.
|
|
||||||
19
.github/workflows/labels.yml
vendored
19
.github/workflows/labels.yml
vendored
@@ -1,19 +0,0 @@
|
|||||||
# Automatically labels PRs based on the configuration file
|
|
||||||
# you are probably looking for 👉 `.github/labeler.yml`
|
|
||||||
name: Label PRs
|
|
||||||
|
|
||||||
on:
|
|
||||||
- pull_request_target
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
triage:
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
pull-requests: write
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
if: github.repository_owner == 'nushell'
|
|
||||||
steps:
|
|
||||||
- uses: actions/labeler@v5
|
|
||||||
with:
|
|
||||||
repo-token: "${{ secrets.GITHUB_TOKEN }}"
|
|
||||||
sync-labels: true
|
|
||||||
30
.github/workflows/milestone.yml
vendored
30
.github/workflows/milestone.yml
vendored
@@ -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@v2
|
|
||||||
if: github.event.issue.state == 'closed'
|
|
||||||
with:
|
|
||||||
action: bind-issue
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
284
.github/workflows/nightly-build.yml
vendored
284
.github/workflows/nightly-build.yml
vendored
@@ -1,284 +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
|
|
||||||
# 5. https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#jobsjob_idneeds
|
|
||||||
#
|
|
||||||
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
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
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'
|
|
||||||
# Map a step output to a job output
|
|
||||||
outputs:
|
|
||||||
skip: ${{ steps.vars.outputs.skip }}
|
|
||||||
build_date: ${{ steps.vars.outputs.build_date }}
|
|
||||||
nightly_tag: ${{ steps.vars.outputs.nightly_tag }}
|
|
||||||
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.105.1
|
|
||||||
|
|
||||||
# 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
|
|
||||||
|
|
||||||
- name: Create Tag and Output Tag Name
|
|
||||||
if: github.repository == 'nushell/nightly'
|
|
||||||
id: vars
|
|
||||||
shell: nu {0}
|
|
||||||
run: |
|
|
||||||
let date = date now | format date %m%d
|
|
||||||
let version = open Cargo.toml | get package.version
|
|
||||||
let sha_short = (git rev-parse --short origin/main | str trim | str substring 0..6)
|
|
||||||
let latest_meta = http get https://api.github.com/repos/nushell/nightly/releases
|
|
||||||
| sort-by -r created_at
|
|
||||||
| where tag_name =~ nightly
|
|
||||||
| get tag_name?.0? | default ''
|
|
||||||
| parse '{version}-nightly.{build}+{hash}'
|
|
||||||
if ($latest_meta.0?.hash? | default '') == $sha_short {
|
|
||||||
print $'(ansi g)Latest nightly build is up-to-date, skip rebuilding.(ansi reset)'
|
|
||||||
$'skip=true(char nl)' o>> $env.GITHUB_OUTPUT
|
|
||||||
exit 0
|
|
||||||
}
|
|
||||||
let prev_ver = $latest_meta.0?.version? | default '0.0.0'
|
|
||||||
let build = if ($latest_meta | is-empty) or ($version != $prev_ver) { 1 } else {
|
|
||||||
($latest_meta | get build?.0? | default 0 | into int) + 1
|
|
||||||
}
|
|
||||||
let nightly_tag = $'($version)-nightly.($build)+($sha_short)'
|
|
||||||
$'build_date=($date)(char nl)' o>> $env.GITHUB_OUTPUT
|
|
||||||
$'nightly_tag=($nightly_tag)(char nl)' o>> $env.GITHUB_OUTPUT
|
|
||||||
if (git ls-remote --tags origin $nightly_tag | is-empty) {
|
|
||||||
ls **/Cargo.toml | each {|file|
|
|
||||||
open --raw $file.name
|
|
||||||
| str replace --all $'version = "($version)"' $'version = "($version)-nightly.($build)"'
|
|
||||||
| save --force $file.name
|
|
||||||
}
|
|
||||||
# Disable the following two workflows for the automatic committed changes
|
|
||||||
rm .github/workflows/ci.yml
|
|
||||||
rm .github/workflows/audit.yml
|
|
||||||
|
|
||||||
git add .
|
|
||||||
git commit -m $'Update version to ($version)-nightly.($build)'
|
|
||||||
git tag -a $nightly_tag -m $'Nightly build from ($sha_short)'
|
|
||||||
git push origin --tags
|
|
||||||
git push origin main -f
|
|
||||||
}
|
|
||||||
|
|
||||||
release:
|
|
||||||
name: Nu
|
|
||||||
needs: prepare
|
|
||||||
if: needs.prepare.outputs.skip != 'true'
|
|
||||||
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
|
|
||||||
- loongarch64-unknown-linux-musl
|
|
||||||
include:
|
|
||||||
- target: aarch64-apple-darwin
|
|
||||||
os: macos-latest
|
|
||||||
- target: x86_64-apple-darwin
|
|
||||||
os: macos-latest
|
|
||||||
- target: x86_64-pc-windows-msvc
|
|
||||||
os: windows-latest
|
|
||||||
- target: aarch64-pc-windows-msvc
|
|
||||||
os: windows-11-arm
|
|
||||||
- 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-22.04
|
|
||||||
- target: loongarch64-unknown-linux-gnu
|
|
||||||
os: ubuntu-22.04
|
|
||||||
- target: loongarch64-unknown-linux-musl
|
|
||||||
os: ubuntu-22.04
|
|
||||||
|
|
||||||
runs-on: ${{matrix.os}}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: main
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Install Wix Toolset 6 for Windows
|
|
||||||
shell: pwsh
|
|
||||||
if: ${{ startsWith(matrix.os, 'windows') }}
|
|
||||||
run: |
|
|
||||||
dotnet tool install --global wix --version 6.0.0
|
|
||||||
dotnet workload install wix
|
|
||||||
$wixPath = "$env:USERPROFILE\.dotnet\tools"
|
|
||||||
echo "$wixPath" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
|
|
||||||
$env:PATH = "$wixPath;$env:PATH"
|
|
||||||
wix --version
|
|
||||||
|
|
||||||
- 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
|
|
||||||
# WARN: Keep the rustflags to prevent from the winget submission error: `CAQuietExec: Error 0xc0000135`
|
|
||||||
with:
|
|
||||||
cache: false
|
|
||||||
rustflags: ''
|
|
||||||
|
|
||||||
- name: Setup Nushell
|
|
||||||
uses: hustcer/setup-nu@v3
|
|
||||||
with:
|
|
||||||
version: 0.105.1
|
|
||||||
|
|
||||||
- name: Release Nu Binary
|
|
||||||
id: nu
|
|
||||||
run: nu .github/workflows/release-pkg.nu
|
|
||||||
env:
|
|
||||||
OS: ${{ matrix.os }}
|
|
||||||
REF: ${{ github.ref }}
|
|
||||||
TARGET: ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: Create an Issue for Release Failure
|
|
||||||
if: ${{ failure() }}
|
|
||||||
uses: JasonEtco/create-an-issue@v2
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
with:
|
|
||||||
update_existing: true
|
|
||||||
search_existing: open
|
|
||||||
filename: .github/AUTO_ISSUE_TEMPLATE/nightly-build-fail.md
|
|
||||||
|
|
||||||
# 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.9
|
|
||||||
if: ${{ startsWith(github.repository, 'nushell/nightly') }}
|
|
||||||
with:
|
|
||||||
prerelease: true
|
|
||||||
files: |
|
|
||||||
${{ steps.nu.outputs.msi }}
|
|
||||||
${{ steps.nu.outputs.archive }}
|
|
||||||
tag_name: ${{ needs.prepare.outputs.nightly_tag }}
|
|
||||||
name: ${{ needs.prepare.outputs.build_date }}-${{ needs.prepare.outputs.nightly_tag }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
sha256sum:
|
|
||||||
needs: [prepare, release]
|
|
||||||
name: Create Sha256sum
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
if: github.repository == 'nushell/nightly'
|
|
||||||
steps:
|
|
||||||
- name: Download Release Archives
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
run: >-
|
|
||||||
gh release download ${{ needs.prepare.outputs.nightly_tag }}
|
|
||||||
--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.9
|
|
||||||
with:
|
|
||||||
draft: false
|
|
||||||
prerelease: true
|
|
||||||
files: SHA256SUMS
|
|
||||||
tag_name: ${{ needs.prepare.outputs.nightly_tag }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
cleanup:
|
|
||||||
name: Cleanup
|
|
||||||
# Should only run in nushell/nightly repo
|
|
||||||
if: github.repository == 'nushell/nightly'
|
|
||||||
needs: [release, sha256sum]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: main
|
|
||||||
|
|
||||||
- name: Setup Nushell
|
|
||||||
uses: hustcer/setup-nu@v3
|
|
||||||
with:
|
|
||||||
version: 0.105.1
|
|
||||||
|
|
||||||
# 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 | slice $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
|
|
||||||
}
|
|
||||||
62
.github/workflows/release-msi.nu
vendored
62
.github/workflows/release-msi.nu
vendored
@@ -1,62 +0,0 @@
|
|||||||
#!/usr/bin/env nu
|
|
||||||
|
|
||||||
# Created: 2025/05/21 19:05:20
|
|
||||||
# Description:
|
|
||||||
# A script to build Windows MSI packages for NuShell. Need wix 6.0 to be installed.
|
|
||||||
# The script will download the specified NuShell release, extract it, and create an MSI package.
|
|
||||||
# Can be run locally or in GitHub Actions.
|
|
||||||
# To run this script locally:
|
|
||||||
# load-env { TARGET: 'x86_64-pc-windows-msvc' REF: '0.103.0' GITHUB_REPOSITORY: 'nushell/nushell' }
|
|
||||||
# nu .github/workflows/release-msi.nu
|
|
||||||
|
|
||||||
def build-msi [] {
|
|
||||||
let target = $env.TARGET
|
|
||||||
# We should read the version from the environment variable first
|
|
||||||
# As we may build the MSI package for a specific version not the latest one
|
|
||||||
let version = $env.MSI_VERSION? | default (open Cargo.toml | get package.version)
|
|
||||||
let arch = if $nu.os-info.arch =~ 'x86_64' { 'x64' } else { 'arm64' }
|
|
||||||
|
|
||||||
print $'Building msi package for (ansi g)($target)(ansi reset) with version (ansi g)($version)(ansi reset) from tag (ansi g)($env.REF)(ansi reset)...'
|
|
||||||
fetch-nu-pkg
|
|
||||||
# Create extra Windows msi release package if dotnet and wix are available
|
|
||||||
let installed = [dotnet wix] | all { (which $in | length) > 0 }
|
|
||||||
if $installed and (wix --version | split row . | first | into int) >= 6 {
|
|
||||||
|
|
||||||
print $'(char nl)Start creating Windows msi package with the following contents...'
|
|
||||||
cd wix; hr-line
|
|
||||||
cp nu/README.txt .
|
|
||||||
ls -f nu/* | print
|
|
||||||
./nu/nu.exe -c $'NU_RELEASE_VERSION=($version) dotnet build -c Release -p:Platform=($arch)'
|
|
||||||
glob **/*.msi | print
|
|
||||||
# Workaround for https://github.com/softprops/action-gh-release/issues/280
|
|
||||||
let wixRelease = (glob **/*.msi | where $it =~ bin | get 0 | str replace --all '\' '/')
|
|
||||||
let msi = $'($wixRelease | path dirname)/nu-($version)-($target).msi'
|
|
||||||
mv $wixRelease $msi
|
|
||||||
print $'MSI archive: ---> ($msi)';
|
|
||||||
# Run only in GitHub Actions
|
|
||||||
if ($env.GITHUB_ACTIONS? | default false | into bool) {
|
|
||||||
echo $"msi=($msi)(char nl)" o>> $env.GITHUB_OUTPUT
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def fetch-nu-pkg [] {
|
|
||||||
mkdir wix/nu
|
|
||||||
# See: https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables#default-environment-variables
|
|
||||||
gh release download $env.REF --repo $env.GITHUB_REPOSITORY --pattern $'*-($env.TARGET).zip' --dir wix/nu
|
|
||||||
cd wix/nu
|
|
||||||
let pkg = ls *.zip | get name.0
|
|
||||||
unzip $pkg
|
|
||||||
rm $pkg
|
|
||||||
ls | print
|
|
||||||
}
|
|
||||||
|
|
||||||
# Print a horizontal line marker
|
|
||||||
def 'hr-line' [
|
|
||||||
--blank-line(-b)
|
|
||||||
] {
|
|
||||||
print $'(ansi g)---------------------------------------------------------------------------->(ansi reset)'
|
|
||||||
if $blank_line { char nl }
|
|
||||||
}
|
|
||||||
|
|
||||||
alias main = build-msi
|
|
||||||
103
.github/workflows/release-msi.yml
vendored
103
.github/workflows/release-msi.yml
vendored
@@ -1,103 +0,0 @@
|
|||||||
#
|
|
||||||
# REF:
|
|
||||||
# 1. https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstrategymatrixinclude
|
|
||||||
#
|
|
||||||
name: Build Windows MSI
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
tag:
|
|
||||||
required: true
|
|
||||||
description: 'Tag to Rebuild MSI'
|
|
||||||
version:
|
|
||||||
description: 'Version of Rebuild MSI'
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
packages: write
|
|
||||||
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
release:
|
|
||||||
name: Nu
|
|
||||||
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
target:
|
|
||||||
- x86_64-pc-windows-msvc
|
|
||||||
- aarch64-pc-windows-msvc
|
|
||||||
extra: ['bin']
|
|
||||||
|
|
||||||
include:
|
|
||||||
- target: x86_64-pc-windows-msvc
|
|
||||||
os: windows-latest
|
|
||||||
- target: aarch64-pc-windows-msvc
|
|
||||||
os: windows-11-arm
|
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Install Wix Toolset 6 for Windows
|
|
||||||
shell: pwsh
|
|
||||||
if: ${{ startsWith(matrix.os, 'windows') }}
|
|
||||||
run: |
|
|
||||||
dotnet tool install --global wix --version 6.0.0
|
|
||||||
dotnet workload install wix
|
|
||||||
$wixPath = "$env:USERPROFILE\.dotnet\tools"
|
|
||||||
echo "$wixPath" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
|
|
||||||
$env:PATH = "$wixPath;$env:PATH"
|
|
||||||
wix --version
|
|
||||||
|
|
||||||
- name: Setup Nushell
|
|
||||||
uses: hustcer/setup-nu@v3
|
|
||||||
with:
|
|
||||||
version: 0.105.1
|
|
||||||
|
|
||||||
- name: Release MSI Packages
|
|
||||||
id: nu
|
|
||||||
run: nu .github/workflows/release-msi.nu
|
|
||||||
env:
|
|
||||||
OS: ${{ matrix.os }}
|
|
||||||
REF: ${{ inputs.tag }}
|
|
||||||
TARGET: ${{ matrix.target }}
|
|
||||||
MSI_VERSION: ${{ inputs.version }}
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
# REF: https://github.com/marketplace/actions/gh-release
|
|
||||||
- name: Publish Archive
|
|
||||||
uses: softprops/action-gh-release@v2.0.5
|
|
||||||
with:
|
|
||||||
tag_name: ${{ inputs.tag }}
|
|
||||||
files: ${{ steps.nu.outputs.msi }}
|
|
||||||
env:
|
|
||||||
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 ${{ inputs.tag }}
|
|
||||||
--repo ${{ github.repository }}
|
|
||||||
--pattern '*'
|
|
||||||
--dir release
|
|
||||||
- name: Create Checksums
|
|
||||||
run: cd release && rm -f SHA256SUMS && shasum -a 256 * > ../SHA256SUMS
|
|
||||||
- name: Publish Checksums
|
|
||||||
uses: softprops/action-gh-release@v2.0.5
|
|
||||||
with:
|
|
||||||
files: SHA256SUMS
|
|
||||||
tag_name: ${{ inputs.tag }}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
255
.github/workflows/release-pkg.nu
vendored
255
.github/workflows/release-pkg.nu
vendored
@@ -6,243 +6,144 @@
|
|||||||
# 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.103.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 wix 6.0 installed: dotnet tool install --global wix --version 6.0.0
|
|
||||||
# then build nu*.exe and the MSI installer by running:
|
|
||||||
# 9. 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
|
|
||||||
# 10. open wix\bin\x64\Release\nu-0.103.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:'
|
|
||||||
print { version: $version, bin: $bin, os: $os, target: $target, src: $src, dist: $dist }; hr-line -b
|
|
||||||
|
|
||||||
# $env
|
# $env
|
||||||
|
|
||||||
let USE_UBUNTU = $os starts-with ubuntu
|
$'(char nl)Packaging ($bin) v($version) for ($target) in ($src)...'; hr-line -b
|
||||||
|
|
||||||
print $'(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 ['ubuntu-latest', 'macos-latest'] {
|
||||||
if $USE_UBUNTU {
|
if $os == 'ubuntu-latest' {
|
||||||
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' => {
|
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://github.com/nushell/integrations/releases/download/build-tools/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://github.com/nushell/integrations/releases/download/build-tools/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
|
|
||||||
}
|
|
||||||
'loongarch64-unknown-linux-musl' => {
|
|
||||||
print $"(ansi g)Downloading LoongArch64 musl cross-compilation toolchain...(ansi reset)"
|
|
||||||
aria2c -q https://github.com/LoongsonLab/oscomp-toolchains-for-oskernel/releases/download/loongarch64-linux-musl-cross-gcc-13.2.0/loongarch64-linux-musl-cross.tgz
|
|
||||||
tar -xf loongarch64-linux-musl-cross.tgz
|
|
||||||
$env.PATH = ($env.PATH | split row (char esep) | prepend $'($env.PWD)/loongarch64-linux-musl-cross/bin')
|
|
||||||
$env.CARGO_TARGET_LOONGARCH64_UNKNOWN_LINUX_MUSL_LINKER = "loongarch64-linux-musl-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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
# Build for Windows without static-link-openssl feature
|
# Build for Windows without static-link-openssl feature
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
if $os =~ 'windows' {
|
if $os in ['windows-latest'] {
|
||||||
cargo-build-nu
|
if ($flags | str trim | empty?) {
|
||||||
|
cargo build --release --all --target $target --features=extra
|
||||||
|
} else {
|
||||||
|
cargo build --release --all --target $target --features=extra $flags
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
# Prepare for the release archive
|
# Prepare for the release archive
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
let suffix = if $os =~ 'windows' { '.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
|
let ver = if $os == 'windows-latest' {
|
||||||
|
(do -i { ./output/nu.exe -c 'version' }) | str collect
|
||||||
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' {
|
|
||||||
(do -i { .\output\nu.exe -c 'version' }) | default '' | str join
|
|
||||||
} else {
|
} else {
|
||||||
(do -i { ./output/nu -c 'version' }) | default '' | str join
|
(do -i { ./output/nu -c 'version' }) | str collect
|
||||||
}
|
}
|
||||||
if ($ver | str trim | is-empty) {
|
if ($ver | str trim | 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 ['ubuntu-latest', 'macos-latest'] {
|
||||||
|
|
||||||
let files = (ls | get name)
|
$'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls
|
||||||
let dest = $'($bin)-($version)-($target)'
|
|
||||||
let archive = $'($dist)/($dest).tar.gz'
|
|
||||||
|
|
||||||
mkdir $dest
|
let archive = $'($dist)/($bin)-($version)-($target).tar.gz'
|
||||||
$files | each {|it| cp -v $it $dest }
|
tar czf $archive *
|
||||||
|
|
||||||
print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls $dest | print
|
|
||||||
|
|
||||||
tar -czf $archive $dest
|
|
||||||
print $'archive: ---> ($archive)'; ls $archive
|
print $'archive: ---> ($archive)'; ls $archive
|
||||||
# REF: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/
|
echo $'::set-output name=archive::($archive)'
|
||||||
echo $"archive=($archive)(char nl)" o>> $env.GITHUB_OUTPUT
|
|
||||||
|
|
||||||
} else if $os =~ 'windows' {
|
} else if $os == 'windows-latest' {
|
||||||
|
|
||||||
let releaseStem = $'($bin)-($version)-($target)'
|
let releaseStem = $'($bin)-($version)-($target)'
|
||||||
let arch = if $nu.os-info.arch =~ 'x86_64' { 'x64' } else { 'arm64' }
|
|
||||||
fetch-less $arch
|
|
||||||
|
|
||||||
print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls | print
|
$'(char nl)Download less related stuffs...'; hr-line
|
||||||
let archive = $'($dist)/($releaseStem).zip'
|
aria2c https://github.com/jftuga/less-Windows/releases/download/less-v590/less.exe -o less.exe
|
||||||
7z a $archive ...(glob *)
|
aria2c https://raw.githubusercontent.com/jftuga/less-Windows/master/LICENSE -o LICENSE-for-less.txt
|
||||||
let pkg = (ls -f $archive | get name)
|
|
||||||
if not ($pkg | is-empty) {
|
|
||||||
# Workaround for https://github.com/softprops/action-gh-release/issues/280
|
|
||||||
let archive = ($pkg | get 0 | str replace --all '\' '/')
|
|
||||||
print $'archive: ---> ($archive)'
|
|
||||||
echo $"archive=($archive)(char nl)" o>> $env.GITHUB_OUTPUT
|
|
||||||
}
|
|
||||||
|
|
||||||
# Create extra Windows msi release package if dotnet and wix are available
|
# Create Windows msi release package
|
||||||
let installed = [dotnet wix] | all { (which $in | length) > 0 }
|
if (get-env _EXTRA_) == 'msi' {
|
||||||
if $installed and (wix --version | split row . | first | into int) >= 6 {
|
|
||||||
|
|
||||||
print $'(char nl)Start creating Windows msi package with the following contents...'
|
let wixRelease = $'($src)/target/wix/($releaseStem).msi'
|
||||||
cd $src; cd wix; hr-line; mkdir nu
|
$'(char nl)Start creating Windows msi package...'
|
||||||
# Wix need the binaries be stored in nu folder
|
cd $src; hr-line
|
||||||
cp -r ($'($dist)/*' | into glob) nu/
|
# Wix need the binaries be stored in target/release/
|
||||||
cp $'($dist)/README.txt' .
|
cp -r $'($dist)/*' target/release/
|
||||||
ls -f nu/* | print
|
cargo install cargo-wix --version 0.3.2
|
||||||
./nu/nu.exe -c $'NU_RELEASE_VERSION=($version) dotnet build -c Release -p:Platform=($arch)'
|
cargo wix --no-build --nocapture --package nu --output $wixRelease
|
||||||
glob **/*.msi | print
|
echo $'::set-output name=archive::($wixRelease)'
|
||||||
# Workaround for https://github.com/softprops/action-gh-release/issues/280
|
|
||||||
let wixRelease = (glob **/*.msi | where $it =~ bin | get 0 | str replace --all '\' '/')
|
|
||||||
let msi = $'($wixRelease | path dirname)/nu-($version)-($target).msi'
|
|
||||||
mv $wixRelease $msi
|
|
||||||
print $'MSI archive: ---> ($msi)';
|
|
||||||
echo $"msi=($msi)(char nl)" o>> $env.GITHUB_OUTPUT
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def fetch-less [
|
|
||||||
arch: string = 'x64' # The architecture to fetch
|
|
||||||
] {
|
|
||||||
let less_zip = $'less-($arch).zip'
|
|
||||||
print $'Fetching less archive: (ansi g)($less_zip)(ansi reset)'
|
|
||||||
let url = $'https://github.com/jftuga/less-Windows/releases/download/less-v668/($less_zip)'
|
|
||||||
http get https://github.com/jftuga/less-Windows/blob/master/LICENSE | save -rf LICENSE-for-less.txt
|
|
||||||
http get $url | save -rf $less_zip
|
|
||||||
unzip $less_zip
|
|
||||||
rm $less_zip lesskey.exe
|
|
||||||
}
|
|
||||||
|
|
||||||
def 'cargo-build-nu' [] {
|
|
||||||
if $os =~ 'windows' {
|
|
||||||
cargo build --release --all --target $target
|
|
||||||
} else {
|
} else {
|
||||||
cargo build --release --all --target $target --features=static-link-openssl
|
|
||||||
|
$'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls
|
||||||
|
let archive = $'($dist)/($releaseStem).zip'
|
||||||
|
7z a $archive *
|
||||||
|
print $'archive: ---> ($archive)';
|
||||||
|
let pkg = (ls -f $archive | get name)
|
||||||
|
if not ($pkg | empty?) {
|
||||||
|
echo $'::set-output name=archive::($pkg | get 0)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def 'cargo-build-nu' [ options: string ] {
|
||||||
|
if ($options | str trim | empty?) {
|
||||||
|
cargo build --release --all --target $target --features=extra,static-link-openssl
|
||||||
|
} else {
|
||||||
|
cargo build --release --all --target $target --features=extra,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 }
|
||||||
}
|
}
|
||||||
|
|
||||||
# Get the specified env key's value or ''
|
# Get the specified env key's value or ''
|
||||||
|
|||||||
116
.github/workflows/release.yml
vendored
116
.github/workflows/release.yml
vendored
@@ -7,94 +7,74 @@ name: Create Release Draft
|
|||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
push:
|
push:
|
||||||
tags:
|
tags: ["[0-9]+.[0-9]+.[0-9]+*"]
|
||||||
- '[0-9]+.[0-9]+.[0-9]+*'
|
|
||||||
- '!*nightly*' # Don't trigger release for nightly tags
|
|
||||||
|
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
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
|
extra: ['bin']
|
||||||
- riscv64gc-unknown-linux-gnu
|
|
||||||
- loongarch64-unknown-linux-gnu
|
|
||||||
- loongarch64-unknown-linux-musl
|
|
||||||
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'
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
- target: aarch64-pc-windows-msvc
|
target_rustflags: ''
|
||||||
os: windows-11-arm
|
- target: x86_64-pc-windows-msvc
|
||||||
|
extra: msi
|
||||||
|
os: windows-latest
|
||||||
|
target_rustflags: ''
|
||||||
- target: x86_64-unknown-linux-gnu
|
- target: x86_64-unknown-linux-gnu
|
||||||
os: ubuntu-22.04
|
os: ubuntu-latest
|
||||||
|
target_rustflags: ''
|
||||||
- target: x86_64-unknown-linux-musl
|
- target: x86_64-unknown-linux-musl
|
||||||
os: ubuntu-22.04
|
os: ubuntu-latest
|
||||||
|
target_rustflags: ''
|
||||||
- target: aarch64-unknown-linux-gnu
|
- target: aarch64-unknown-linux-gnu
|
||||||
os: ubuntu-22.04
|
os: ubuntu-latest
|
||||||
- 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-latest
|
||||||
- target: armv7-unknown-linux-musleabihf
|
target_rustflags: ''
|
||||||
os: ubuntu-22.04
|
|
||||||
- target: riscv64gc-unknown-linux-gnu
|
|
||||||
os: ubuntu-22.04
|
|
||||||
- target: loongarch64-unknown-linux-gnu
|
|
||||||
os: ubuntu-22.04
|
|
||||||
- target: loongarch64-unknown-linux-musl
|
|
||||||
os: ubuntu-22.04
|
|
||||||
|
|
||||||
runs-on: ${{matrix.os}}
|
runs-on: ${{matrix.os}}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v3.0.2
|
||||||
|
|
||||||
- name: Install Wix Toolset 6 for Windows
|
- name: Install Rust Toolchain Components
|
||||||
shell: pwsh
|
uses: actions-rs/toolchain@v1.0.6
|
||||||
if: ${{ startsWith(matrix.os, 'windows') }}
|
|
||||||
run: |
|
|
||||||
dotnet tool install --global wix --version 6.0.0
|
|
||||||
dotnet workload install wix
|
|
||||||
$wixPath = "$env:USERPROFILE\.dotnet\tools"
|
|
||||||
echo "$wixPath" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
|
|
||||||
$env:PATH = "$wixPath;$env:PATH"
|
|
||||||
wix --version
|
|
||||||
|
|
||||||
- name: Update Rust Toolchain Target
|
|
||||||
run: |
|
|
||||||
echo "targets = ['${{matrix.target}}']" >> rust-toolchain.toml
|
|
||||||
|
|
||||||
- name: Setup Rust toolchain
|
|
||||||
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
|
|
||||||
# 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@v1
|
||||||
with:
|
with:
|
||||||
version: 0.105.1
|
version: 0.63.0
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
- name: Release Nu Binary
|
- name: Release Nu Binary
|
||||||
id: nu
|
id: nu
|
||||||
@@ -103,39 +83,15 @@ jobs:
|
|||||||
OS: ${{ matrix.os }}
|
OS: ${{ matrix.os }}
|
||||||
REF: ${{ github.ref }}
|
REF: ${{ github.ref }}
|
||||||
TARGET: ${{ matrix.target }}
|
TARGET: ${{ matrix.target }}
|
||||||
|
_EXTRA_: ${{ matrix.extra }}
|
||||||
|
TARGET_RUSTFLAGS: ${{ matrix.target_rustflags }}
|
||||||
|
|
||||||
# WARN: Don't upgrade this action due to the release per asset issue.
|
# REF: https://github.com/marketplace/actions/gh-release
|
||||||
# See: https://github.com/softprops/action-gh-release/issues/445
|
|
||||||
- name: Publish Archive
|
- name: Publish Archive
|
||||||
uses: softprops/action-gh-release@v2.0.5
|
uses: softprops/action-gh-release@v1
|
||||||
if: ${{ startsWith(github.ref, 'refs/tags/') }}
|
if: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||||
with:
|
with:
|
||||||
draft: true
|
draft: true
|
||||||
files: |
|
files: ${{ steps.nu.outputs.archive }}
|
||||||
${{ steps.nu.outputs.msi }}
|
|
||||||
${{ steps.nu.outputs.archive }}
|
|
||||||
env:
|
|
||||||
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.5
|
|
||||||
with:
|
|
||||||
draft: true
|
|
||||||
files: SHA256SUMS
|
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|||||||
28
.github/workflows/stale.yml
vendored
Normal file
28
.github/workflows/stale.yml
vendored
Normal 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'
|
||||||
13
.github/workflows/typos.yml
vendored
13
.github/workflows/typos.yml
vendored
@@ -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.34.0
|
|
||||||
31
.github/workflows/winget-submission.yml
vendored
31
.github/workflows/winget-submission.yml
vendored
@@ -1,34 +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
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
packages: write
|
|
||||||
pull-requests: write
|
|
||||||
|
|
||||||
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://aka.ms/wingetcreate/latest -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: nushell
|
|
||||||
|
|||||||
27
.gitignore
vendored
27
.gitignore
vendored
@@ -22,37 +22,10 @@ debian/nu/
|
|||||||
# VSCode's IDE items
|
# VSCode's IDE items
|
||||||
.vscode/*
|
.vscode/*
|
||||||
|
|
||||||
# JetBrains' Fleet IDE
|
|
||||||
.fleet/*
|
|
||||||
|
|
||||||
# Visual Studio Extension SourceGear Rust items
|
|
||||||
VSWorkspaceSettings.json
|
|
||||||
unstable_cargo_features.txt
|
|
||||||
|
|
||||||
# Helix configuration folder
|
# Helix configuration folder
|
||||||
.helix/*
|
.helix/*
|
||||||
.helix
|
.helix
|
||||||
wix/bin/
|
|
||||||
wix/obj/
|
|
||||||
wix/nu/
|
|
||||||
|
|
||||||
# Coverage tools
|
# Coverage tools
|
||||||
lcov.info
|
lcov.info
|
||||||
tarpaulin-report.html
|
tarpaulin-report.html
|
||||||
|
|
||||||
# benchmarking
|
|
||||||
/tango
|
|
||||||
|
|
||||||
# Visual Studio
|
|
||||||
.vs/*
|
|
||||||
*.rsproj
|
|
||||||
*.rsproj.user
|
|
||||||
*.sln
|
|
||||||
*.code-workspace
|
|
||||||
|
|
||||||
# direnv
|
|
||||||
.direnv/
|
|
||||||
.envrc
|
|
||||||
|
|
||||||
# pre-commit-hooks
|
|
||||||
.pre-commit-config.yaml
|
|
||||||
|
|||||||
26
CITATION.cff
26
CITATION.cff
@@ -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
|
|
||||||
202
CONTRIBUTING.md
202
CONTRIBUTING.md
@@ -1,41 +1,8 @@
|
|||||||
# Contributing
|
# Contributing
|
||||||
|
|
||||||
Welcome to Nushell and thank you for considering contributing!
|
Welcome to Nushell!
|
||||||
|
|
||||||
## Table of contents
|
To get live support from the community see our [Discord](https://discordapp.com/invite/NtAbbGn), [Twitter](https://twitter.com/nu_shell) or file an issue or feature request here on [GitHub](https://github.com/nushell/nushell/issues/new/choose)!
|
||||||
- [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.
|
|
||||||
This saves both your and our time if we realize the change needs to go another direction before spending time on it.
|
|
||||||
So, please, reach out and tell us what you want to do.
|
|
||||||
This will significantly increase the chance of your PR being accepted.
|
|
||||||
|
|
||||||
The review process can be summarized as follows:
|
|
||||||
1. You want to make some change to Nushell that is more involved than simple bug-fixing.
|
|
||||||
2. Go to [Discord](https://discordapp.com/invite/NtAbbGn) or a [GitHub issue](https://github.com/nushell/nushell/issues/new/choose) and chat with some core team members and/or other contributors about it.
|
|
||||||
3. After getting a green light from the core team, implement the feature, open a pull request (PR) and write a concise but comprehensive description of the change.
|
|
||||||
4. If your PR includes any user-facing features (such as adding a flag to a command), clearly list them in the PR description.
|
|
||||||
5. Then, core team members and other regular contributors will review the PR and suggest changes.
|
|
||||||
6. When we all agree, the PR will be merged.
|
|
||||||
7. If your PR includes any user-facing features, make sure the changes are also reflected in [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged.
|
|
||||||
8. Congratulate yourself, you just improved Nushell! :-)
|
|
||||||
|
|
||||||
## Developing
|
## Developing
|
||||||
|
|
||||||
@@ -49,188 +16,53 @@ cd nushell
|
|||||||
cargo build
|
cargo build
|
||||||
```
|
```
|
||||||
|
|
||||||
### 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.
|
|
||||||
|
|
||||||
Tests can be found in different places:
|
|
||||||
* `/tests`
|
|
||||||
* command examples
|
|
||||||
* 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.
|
|
||||||
|
|
||||||
### 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 extra features. Currently extra features include dataframes and sqlite database support.
|
||||||
|
```shell
|
||||||
|
cargo run --features=extra
|
||||||
|
```
|
||||||
|
|
||||||
- Run Clippy on Nushell:
|
- Run Clippy on Nushell:
|
||||||
|
|
||||||
```nushell
|
```shell
|
||||||
cargo clippy --workspace -- -D warnings -D clippy::unwrap_used
|
cargo clippy --workspace --features=extra -- -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 --features=extra
|
||||||
```
|
|
||||||
|
|
||||||
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 --features=extra -- --log-level trace
|
||||||
```
|
```
|
||||||
|
|
||||||
- To redirect trace logs to a file, enable the `--log-target file` switch.
|
|
||||||
```nushell
|
|
||||||
cargo run --release -- --log-level trace --log-target file
|
|
||||||
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.
|
|
||||||
|
|||||||
7983
Cargo.lock
generated
7983
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
361
Cargo.toml
361
Cargo.toml
@@ -1,316 +1,104 @@
|
|||||||
[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 = "2024"
|
edition = "2018"
|
||||||
exclude = ["images"]
|
exclude = ["images"]
|
||||||
homepage = "https://www.nushell.sh"
|
homepage = "https://www.nushell.sh"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
name = "nu"
|
name = "nu"
|
||||||
|
readme = "README.md"
|
||||||
repository = "https://github.com/nushell/nushell"
|
repository = "https://github.com/nushell/nushell"
|
||||||
rust-version = "1.86.0"
|
rust-version = "1.60"
|
||||||
version = "0.106.0"
|
version = "0.66.2"
|
||||||
|
|
||||||
# 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
|
||||||
|
|
||||||
[package.metadata.binstall]
|
|
||||||
pkg-url = "{ repo }/releases/download/{ version }/{ name }-{ version }-{ target }.{ archive-format }"
|
|
||||||
pkg-fmt = "tgz"
|
|
||||||
|
|
||||||
[package.metadata.binstall.overrides.x86_64-pc-windows-msvc]
|
|
||||||
pkg-fmt = "zip"
|
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"crates/nu_plugin_custom_values",
|
"crates/nu-cli",
|
||||||
"crates/nu_plugin_example",
|
"crates/nu-engine",
|
||||||
"crates/nu_plugin_formats",
|
"crates/nu-parser",
|
||||||
"crates/nu_plugin_gstat",
|
"crates/nu-system",
|
||||||
"crates/nu_plugin_inc",
|
"crates/nu-command",
|
||||||
"crates/nu_plugin_polars",
|
"crates/nu-protocol",
|
||||||
"crates/nu_plugin_query",
|
"crates/nu-plugin",
|
||||||
"crates/nu_plugin_stress_internals",
|
"crates/nu_plugin_inc",
|
||||||
"crates/nu-cli",
|
"crates/nu_plugin_gstat",
|
||||||
"crates/nu-cmd-base",
|
"crates/nu_plugin_example",
|
||||||
"crates/nu-cmd-extra",
|
"crates/nu_plugin_query",
|
||||||
"crates/nu-cmd-lang",
|
"crates/nu_plugin_custom_values",
|
||||||
"crates/nu-cmd-plugin",
|
"crates/nu-utils",
|
||||||
"crates/nu-color-config",
|
|
||||||
"crates/nu-command",
|
|
||||||
"crates/nu-derive-value",
|
|
||||||
"crates/nu-engine",
|
|
||||||
"crates/nu-experimental",
|
|
||||||
"crates/nu-explore",
|
|
||||||
"crates/nu-json",
|
|
||||||
"crates/nu-lsp",
|
|
||||||
"crates/nu-parser",
|
|
||||||
"crates/nu-plugin-core",
|
|
||||||
"crates/nu-plugin-engine",
|
|
||||||
"crates/nu-plugin-protocol",
|
|
||||||
"crates/nu-plugin-test-support",
|
|
||||||
"crates/nu-plugin",
|
|
||||||
"crates/nu-pretty-hex",
|
|
||||||
"crates/nu-protocol",
|
|
||||||
"crates/nu-std",
|
|
||||||
"crates/nu-system",
|
|
||||||
"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.9"
|
|
||||||
anyhow = "1.0.82"
|
|
||||||
base64 = "0.22.1"
|
|
||||||
bracoxide = "0.1.6"
|
|
||||||
brotli = "7.0"
|
|
||||||
byteorder = "1.5"
|
|
||||||
bytes = "1"
|
|
||||||
bytesize = "1.3.3"
|
|
||||||
calamine = "0.28"
|
|
||||||
chardetng = "0.1.17"
|
|
||||||
chrono = { default-features = false, version = "0.4.34" }
|
|
||||||
chrono-humanize = "0.2.3"
|
|
||||||
chrono-tz = "0.10"
|
|
||||||
crossbeam-channel = "0.5.8"
|
|
||||||
crossterm = "0.28.1"
|
|
||||||
csv = "1.3"
|
|
||||||
ctrlc = "3.4"
|
|
||||||
devicons = "0.6.12"
|
|
||||||
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.14"
|
|
||||||
filesize = "0.2"
|
|
||||||
filetime = "0.2"
|
|
||||||
heck = "0.5.0"
|
|
||||||
human-date-parser = "0.3.0"
|
|
||||||
indexmap = "2.10"
|
|
||||||
indicatif = "0.17"
|
|
||||||
interprocess = "2.2.0"
|
|
||||||
is_executable = "1.0"
|
|
||||||
itertools = "0.14"
|
|
||||||
libc = "0.2"
|
|
||||||
libproc = "0.14"
|
|
||||||
log = "0.4"
|
|
||||||
lru = "0.12"
|
|
||||||
lscolors = { version = "0.20", default-features = false }
|
|
||||||
lsp-server = "0.7.8"
|
|
||||||
lsp-types = { version = "0.97.0", features = ["proposed"] }
|
|
||||||
lsp-textdocument = "0.4.2"
|
|
||||||
mach2 = "0.4"
|
|
||||||
md5 = { version = "0.10", package = "md-5" }
|
|
||||||
miette = "7.6"
|
|
||||||
mime = "0.3.17"
|
|
||||||
mime_guess = "2.0"
|
|
||||||
mockito = { version = "1.7", default-features = false }
|
|
||||||
multipart-rs = "0.1.13"
|
|
||||||
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"
|
|
||||||
nucleo-matcher = "0.3"
|
|
||||||
num-format = "0.4"
|
|
||||||
num-traits = "0.2"
|
|
||||||
oem_cp = "2.0.0"
|
|
||||||
omnipath = "0.1"
|
|
||||||
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-error2 = "2.0"
|
|
||||||
proc-macro2 = "1.0"
|
|
||||||
procfs = "0.17.0"
|
|
||||||
pwd = "1.3"
|
|
||||||
quick-xml = "0.37.5"
|
|
||||||
quickcheck = "1.0"
|
|
||||||
quickcheck_macros = "1.1"
|
|
||||||
quote = "1.0"
|
|
||||||
rand = "0.9"
|
|
||||||
getrandom = "0.2" # pick same version that rand requires
|
|
||||||
rand_chacha = "0.9"
|
|
||||||
ratatui = "0.29"
|
|
||||||
rayon = "1.10"
|
|
||||||
reedline = "0.41.0"
|
|
||||||
rmp = "0.8"
|
|
||||||
rmp-serde = "1.3"
|
|
||||||
roxmltree = "0.20"
|
|
||||||
rstest = { version = "0.23", default-features = false }
|
|
||||||
rstest_reuse = "0.7"
|
|
||||||
rusqlite = "0.31"
|
|
||||||
rust-embed = "8.7.0"
|
|
||||||
rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] }
|
|
||||||
rustls-native-certs = "0.8"
|
|
||||||
scopeguard = { version = "1.2.0" }
|
|
||||||
serde = { version = "1.0" }
|
|
||||||
serde_json = "1.0.97"
|
|
||||||
serde_urlencoded = "0.7.1"
|
|
||||||
serde_yaml = "0.9.33"
|
|
||||||
sha2 = "0.10"
|
|
||||||
strip-ansi-escapes = "0.2.1"
|
|
||||||
strum = "0.26"
|
|
||||||
strum_macros = "0.26"
|
|
||||||
syn = "2.0"
|
|
||||||
sysinfo = "0.36"
|
|
||||||
tabled = { version = "0.20", default-features = false }
|
|
||||||
tempfile = "3.20"
|
|
||||||
thiserror = "2.0.12"
|
|
||||||
titlecase = "3.6"
|
|
||||||
toml = "0.8"
|
|
||||||
trash = "5.2"
|
|
||||||
update-informer = { version = "1.3.0", default-features = false, features = ["github", "ureq"] }
|
|
||||||
umask = "2.1"
|
|
||||||
unicode-segmentation = "1.12"
|
|
||||||
unicode-width = "0.2"
|
|
||||||
ureq = { version = "2.12", default-features = false, features = ["socks-proxy"] }
|
|
||||||
url = "2.2"
|
|
||||||
uu_cp = "0.0.30"
|
|
||||||
uu_mkdir = "0.0.30"
|
|
||||||
uu_mktemp = "0.0.30"
|
|
||||||
uu_mv = "0.0.30"
|
|
||||||
uu_touch = "0.0.30"
|
|
||||||
uu_whoami = "0.0.30"
|
|
||||||
uu_uname = "0.0.30"
|
|
||||||
uucore = "0.0.30"
|
|
||||||
uuid = "1.16.0"
|
|
||||||
v_htmlescape = "0.15.0"
|
|
||||||
wax = "0.6"
|
|
||||||
web-time = "1.1.0"
|
|
||||||
which = "8.0.0"
|
|
||||||
windows = "0.56"
|
|
||||||
windows-sys = "0.48"
|
|
||||||
winreg = "0.52"
|
|
||||||
memchr = "2.7.4"
|
|
||||||
webpki-roots = "1.0"
|
|
||||||
|
|
||||||
[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"
|
|
||||||
used_underscore_binding = "warn"
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
nu-cli = { path = "./crates/nu-cli", version = "0.106.0" }
|
chrono = { version = "0.4.19", features = ["serde"] }
|
||||||
nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.106.0" }
|
crossterm = "0.23.0"
|
||||||
nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.106.0" }
|
ctrlc = "3.2.1"
|
||||||
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.106.0" }
|
log = "0.4"
|
||||||
nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.106.0", optional = true }
|
miette = "5.1.0"
|
||||||
nu-command = { path = "./crates/nu-command", version = "0.106.0", default-features = false, features = ["os"] }
|
nu-ansi-term = "0.46.0"
|
||||||
nu-engine = { path = "./crates/nu-engine", version = "0.106.0" }
|
nu-cli = { path="./crates/nu-cli", version = "0.66.2" }
|
||||||
nu-experimental = { path = "./crates/nu-experimental", version = "0.106.0" }
|
nu-color-config = { path = "./crates/nu-color-config", version = "0.66.2" }
|
||||||
nu-explore = { path = "./crates/nu-explore", version = "0.106.0" }
|
nu-command = { path="./crates/nu-command", version = "0.66.3" }
|
||||||
nu-lsp = { path = "./crates/nu-lsp/", version = "0.106.0" }
|
nu-engine = { path="./crates/nu-engine", version = "0.66.2" }
|
||||||
nu-parser = { path = "./crates/nu-parser", version = "0.106.0" }
|
nu-json = { path="./crates/nu-json", version = "0.66.2" }
|
||||||
nu-path = { path = "./crates/nu-path", version = "0.106.0" }
|
nu-parser = { path="./crates/nu-parser", version = "0.66.2" }
|
||||||
nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.106.0" }
|
nu-path = { path="./crates/nu-path", version = "0.66.2" }
|
||||||
nu-protocol = { path = "./crates/nu-protocol", version = "0.106.0" }
|
nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.66.2" }
|
||||||
nu-std = { path = "./crates/nu-std", version = "0.106.0" }
|
nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.66.2" }
|
||||||
nu-system = { path = "./crates/nu-system", version = "0.106.0" }
|
nu-protocol = { path = "./crates/nu-protocol", version = "0.66.2" }
|
||||||
nu-utils = { path = "./crates/nu-utils", version = "0.106.0" }
|
nu-system = { path = "./crates/nu-system", version = "0.66.2" }
|
||||||
reedline = { workspace = true, features = ["bashisms", "sqlite"] }
|
nu-table = { path = "./crates/nu-table", version = "0.66.2" }
|
||||||
|
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.66.2" }
|
||||||
crossterm = { workspace = true }
|
nu-utils = { path = "./crates/nu-utils", version = "0.66.2" }
|
||||||
ctrlc = { workspace = true }
|
reedline = { version = "0.9.0", features = ["bashisms", "sqlite"]}
|
||||||
dirs = { workspace = true }
|
pretty_env_logger = "0.4.0"
|
||||||
log = { workspace = true }
|
rayon = "1.5.1"
|
||||||
miette = { workspace = true, features = ["fancy-no-backtrace", "fancy"] }
|
is_executable = "1.0.1"
|
||||||
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]
|
|
||||||
winresource = "0.1"
|
|
||||||
|
|
||||||
[target.'cfg(target_family = "unix")'.dependencies]
|
|
||||||
nix = { workspace = true, default-features = false, features = [
|
|
||||||
"signal",
|
|
||||||
"process",
|
|
||||||
"fs",
|
|
||||||
"term",
|
|
||||||
] }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
nu-test-support = { path = "./crates/nu-test-support", version = "0.106.0" }
|
nu-test-support = { path="./crates/nu-test-support", version = "0.66.2" }
|
||||||
nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.106.0" }
|
tempfile = "3.2.0"
|
||||||
nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.106.0" }
|
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 = "0.15.0"
|
||||||
fancy-regex = { workspace = true }
|
itertools = "0.10.3"
|
||||||
rstest = { workspace = true, default-features = false }
|
|
||||||
serial_test = "3.2"
|
[target.'cfg(windows)'.build-dependencies]
|
||||||
tempfile = { workspace = true }
|
winres = "0.1"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
# Enable all features while still avoiding mutually exclusive features.
|
plugin = ["nu-plugin", "nu-cli/plugin", "nu-parser/plugin", "nu-command/plugin", "nu-protocol/plugin", "nu-engine/plugin"]
|
||||||
# Use this if `--all-features` fails.
|
default = ["plugin", "which-support", "trash-support"]
|
||||||
full = ["plugin", "rustls-tls", "system-clipboard", "trash-support", "sqlite"]
|
|
||||||
|
|
||||||
plugin = [
|
|
||||||
# crates
|
|
||||||
"dep:nu-cmd-plugin",
|
|
||||||
"dep:nu-plugin-engine",
|
|
||||||
|
|
||||||
# features
|
|
||||||
"nu-cli/plugin",
|
|
||||||
"nu-cmd-lang/plugin",
|
|
||||||
"nu-command/plugin",
|
|
||||||
"nu-engine/plugin",
|
|
||||||
"nu-engine/plugin",
|
|
||||||
"nu-parser/plugin",
|
|
||||||
"nu-protocol/plugin",
|
|
||||||
]
|
|
||||||
|
|
||||||
native-tls = ["nu-command/native-tls"]
|
|
||||||
rustls-tls = ["nu-command/rustls-tls"]
|
|
||||||
|
|
||||||
default = [
|
|
||||||
"plugin",
|
|
||||||
"trash-support",
|
|
||||||
"sqlite",
|
|
||||||
"rustls-tls"
|
|
||||||
]
|
|
||||||
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
|
extra = ["default", "dataframe", "database"]
|
||||||
|
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"]
|
||||||
|
|
||||||
# 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",
|
|
||||||
]
|
|
||||||
|
|
||||||
# Stable (Default)
|
# Stable (Default)
|
||||||
|
which-support = ["nu-command/which-support"]
|
||||||
trash-support = ["nu-command/trash-support"]
|
trash-support = ["nu-command/trash-support"]
|
||||||
|
|
||||||
# SQLite commands for nushell
|
# Extra
|
||||||
sqlite = ["nu-command/sqlite", "nu-std/sqlite"]
|
|
||||||
|
# Dataframe feature for nushell
|
||||||
|
dataframe = ["nu-command/dataframe"]
|
||||||
|
|
||||||
|
# Database commands for nushell
|
||||||
|
database = ["nu-command/database"]
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
opt-level = "s" # Optimize for size
|
opt-level = "s" # Optimize for size
|
||||||
strip = "debuginfo"
|
strip = "debuginfo"
|
||||||
lto = "thin"
|
lto = "thin"
|
||||||
|
|
||||||
@@ -332,16 +120,3 @@ 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
|
|
||||||
# changing versions in each sub-crate of the workspace is tedious
|
|
||||||
[patch.crates-io]
|
|
||||||
# reedline = { git = "https://github.com/nushell/reedline", 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
|
|
||||||
|
|||||||
18
Cross.toml
18
Cross.toml
@@ -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"
|
|
||||||
]
|
|
||||||
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2019 - 2025 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
|
||||||
|
|||||||
184
README.md
184
README.md
@@ -1,27 +1,27 @@
|
|||||||
# Nushell <!-- omit in toc -->
|
# Nushell <!-- omit in toc -->
|
||||||
[](https://crates.io/crates/nu)
|
[](https://crates.io/crates/nu)
|
||||||
[](https://github.com/nushell/nushell/actions)
|

|
||||||
[](https://github.com/nushell/nushell/actions/workflows/nightly-build.yml)
|
|
||||||
[](https://discord.gg/NtAbbGn)
|
[](https://discord.gg/NtAbbGn)
|
||||||
[](https://changelog.com/podcast/363)
|
[](https://changelog.com/podcast/363)
|
||||||
[](https://github.com/nushell/nushell/graphs/commit-activity)
|
[](https://twitter.com/nu_shell)
|
||||||
[](https://github.com/nushell/nushell/graphs/contributors)
|

|
||||||
|

|
||||||
|
|
||||||
A new type of shell.
|
A new type of shell.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## 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)
|
||||||
@@ -32,9 +32,9 @@ 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); 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!
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -47,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:
|
||||||
|
|
||||||
[](https://repology.org/project/nushell/versions)
|
[](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/default_files)
|
|
||||||
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
|
||||||
@@ -88,50 +71,50 @@ Additionally, commands can output structured data (you can think of this as a th
|
|||||||
Commands that work in the pipeline fit into one of three categories:
|
Commands that work in the pipeline fit into one of three categories:
|
||||||
|
|
||||||
- Commands that produce a stream (e.g., `ls`)
|
- Commands that produce a stream (e.g., `ls`)
|
||||||
- Commands that filter a stream (e.g., `where type == "dir"`)
|
- Commands that filter a stream (eg, `where type == "dir"`)
|
||||||
- Commands that consume the output of the pipeline (e.g., `table`)
|
- Commands that consume the output of the pipeline (e.g., `table`)
|
||||||
|
|
||||||
Commands are separated by the pipe symbol (`|`) to denote a pipeline flowing left to right.
|
Commands are separated by the pipe symbol (`|`) to denote a pipeline flowing left to right.
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
ls | where type == "dir" | table
|
> ls | where type == "dir" | table
|
||||||
# => ╭────┬──────────┬──────┬─────────┬───────────────╮
|
╭────┬──────────┬──────┬─────────┬───────────────╮
|
||||||
# => │ # │ name │ type │ size │ modified │
|
│ # │ name │ type │ size │ modified │
|
||||||
# => ├────┼──────────┼──────┼─────────┼───────────────┤
|
├────┼──────────┼──────┼─────────┼───────────────┤
|
||||||
# => │ 0 │ .cargo │ dir │ 0 B │ 9 minutes ago │
|
│ 0 │ .cargo │ dir │ 0 B │ 9 minutes ago │
|
||||||
# => │ 1 │ assets │ dir │ 0 B │ 2 weeks ago │
|
│ 1 │ assets │ dir │ 0 B │ 2 weeks ago │
|
||||||
# => │ 2 │ crates │ dir │ 4.0 KiB │ 2 weeks ago │
|
│ 2 │ crates │ dir │ 4.0 KiB │ 2 weeks ago │
|
||||||
# => │ 3 │ docker │ dir │ 0 B │ 2 weeks ago │
|
│ 3 │ docker │ dir │ 0 B │ 2 weeks ago │
|
||||||
# => │ 4 │ docs │ dir │ 0 B │ 2 weeks ago │
|
│ 4 │ docs │ dir │ 0 B │ 2 weeks ago │
|
||||||
# => │ 5 │ images │ dir │ 0 B │ 2 weeks ago │
|
│ 5 │ images │ dir │ 0 B │ 2 weeks ago │
|
||||||
# => │ 6 │ pkg_mgrs │ dir │ 0 B │ 2 weeks ago │
|
│ 6 │ pkg_mgrs │ dir │ 0 B │ 2 weeks ago │
|
||||||
# => │ 7 │ samples │ dir │ 0 B │ 2 weeks ago │
|
│ 7 │ samples │ dir │ 0 B │ 2 weeks ago │
|
||||||
# => │ 8 │ src │ dir │ 4.0 KiB │ 2 weeks ago │
|
│ 8 │ src │ dir │ 4.0 KiB │ 2 weeks ago │
|
||||||
# => │ 9 │ target │ dir │ 0 B │ a day ago │
|
│ 9 │ target │ dir │ 0 B │ a day ago │
|
||||||
# => │ 10 │ tests │ dir │ 4.0 KiB │ 2 weeks ago │
|
│ 10 │ tests │ dir │ 4.0 KiB │ 2 weeks ago │
|
||||||
# => │ 11 │ wix │ dir │ 0 B │ 2 weeks ago │
|
│ 11 │ wix │ dir │ 0 B │ 2 weeks ago │
|
||||||
# => ╰────┴──────────┴──────┴─────────┴───────────────╯
|
╰────┴──────────┴──────┴─────────┴───────────────╯
|
||||||
```
|
```
|
||||||
|
|
||||||
Because most of the time you'll want to see the output of a pipeline, `table` is assumed.
|
Because most of the time you'll want to see the output of a pipeline, `table` is assumed.
|
||||||
We could have also written the above:
|
We could have also written the above:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
ls | where type == "dir"
|
> ls | where type == "dir"
|
||||||
```
|
```
|
||||||
|
|
||||||
Being able to use the same commands and compose them differently is an important philosophy in Nu.
|
Being able to use the same commands and compose them differently is an important philosophy in Nu.
|
||||||
For example, we could use the built-in `ps` command to get a list of the running processes, using the same `where` as above.
|
For example, we could use the built-in `ps` command to get a list of the running processes, using the same `where` as above.
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
ps | where cpu > 0
|
> ps | where cpu > 0
|
||||||
# => ╭───┬───────┬───────────┬───────┬───────────┬───────────╮
|
╭───┬───────┬───────────┬───────┬───────────┬───────────╮
|
||||||
# => │ # │ pid │ name │ cpu │ mem │ virtual │
|
│ # │ pid │ name │ cpu │ mem │ virtual │
|
||||||
# => ├───┼───────┼───────────┼───────┼───────────┼───────────┤
|
├───┼───────┼───────────┼───────┼───────────┼───────────┤
|
||||||
# => │ 0 │ 2240 │ Slack.exe │ 16.40 │ 178.3 MiB │ 232.6 MiB │
|
│ 0 │ 2240 │ Slack.exe │ 16.40 │ 178.3 MiB │ 232.6 MiB │
|
||||||
# => │ 1 │ 16948 │ Slack.exe │ 16.32 │ 205.0 MiB │ 197.9 MiB │
|
│ 1 │ 16948 │ Slack.exe │ 16.32 │ 205.0 MiB │ 197.9 MiB │
|
||||||
# => │ 2 │ 17700 │ nu.exe │ 3.77 │ 26.1 MiB │ 8.8 MiB │
|
│ 2 │ 17700 │ nu.exe │ 3.77 │ 26.1 MiB │ 8.8 MiB │
|
||||||
# => ╰───┴───────┴───────────┴───────┴───────────┴───────────╯
|
╰───┴───────┴───────────┴───────┴───────────┴───────────╯
|
||||||
```
|
```
|
||||||
|
|
||||||
### Opening files
|
### Opening files
|
||||||
@@ -140,46 +123,45 @@ Nu can load file and URL contents as raw text or structured data (if it recogniz
|
|||||||
For example, you can load a .toml file as structured data and explore it:
|
For example, you can load a .toml file as structured data and explore it:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
open Cargo.toml
|
> open Cargo.toml
|
||||||
# => ╭──────────────────┬────────────────────╮
|
╭──────────────────┬────────────────────╮
|
||||||
# => │ bin │ [table 1 row] │
|
│ bin │ [table 1 row] │
|
||||||
# => │ dependencies │ {record 25 fields} │
|
│ dependencies │ {record 24 fields} │
|
||||||
# => │ dev-dependencies │ {record 8 fields} │
|
│ dev-dependencies │ {record 8 fields} │
|
||||||
# => │ features │ {record 10 fields} │
|
│ features │ {record 10 fields} │
|
||||||
# => │ package │ {record 13 fields} │
|
│ package │ {record 13 fields} │
|
||||||
# => │ patch │ {record 1 field} │
|
│ profile │ {record 3 fields} │
|
||||||
# => │ profile │ {record 3 fields} │
|
│ target │ {record 2 fields} │
|
||||||
# => │ target │ {record 3 fields} │
|
│ workspace │ {record 1 field} │
|
||||||
# => │ workspace │ {record 1 field} │
|
╰──────────────────┴────────────────────╯
|
||||||
# => ╰──────────────────┴────────────────────╯
|
|
||||||
```
|
```
|
||||||
|
|
||||||
We can pipe this into a command that gets the contents of one of the columns:
|
We can pipe this into a command that gets the contents of one of the columns:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
open Cargo.toml | get package
|
> open Cargo.toml | get package
|
||||||
# => ╭───────────────┬────────────────────────────────────╮
|
╭───────────────┬────────────────────────────────────╮
|
||||||
# => │ authors │ [list 1 item] │
|
│ authors │ [list 1 item] │
|
||||||
# => │ 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 │ 2018 │
|
│ edition │ 2018 │
|
||||||
# => │ exclude │ [list 1 item] │
|
│ exclude │ [list 1 item] │
|
||||||
# => │ homepage │ https://www.nushell.sh │
|
│ homepage │ https://www.nushell.sh │
|
||||||
# => │ license │ MIT │
|
│ license │ MIT │
|
||||||
# => │ metadata │ {record 1 field} │
|
│ name │ nu │
|
||||||
# => │ name │ nu │
|
│ readme │ README.md │
|
||||||
# => │ repository │ https://github.com/nushell/nushell │
|
│ repository │ https://github.com/nushell/nushell │
|
||||||
# => │ rust-version │ 1.60 │
|
│ rust-version │ 1.60 │
|
||||||
# => │ version │ 0.72.0 │
|
│ version │ 0.63.1 │
|
||||||
# => ╰───────────────┴────────────────────────────────────╯
|
╰───────────────┴────────────────────────────────────╯
|
||||||
```
|
```
|
||||||
|
|
||||||
And if needed we can drill down further:
|
And if needed we can drill down further:
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
open Cargo.toml | get package.version
|
> open Cargo.toml | get package.version
|
||||||
# => 0.72.0
|
0.63.1
|
||||||
```
|
```
|
||||||
|
|
||||||
### Plugins
|
### Plugins
|
||||||
@@ -191,14 +173,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.
|
||||||
|
|
||||||
@@ -208,6 +187,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, but input/output isn't checked |
|
||||||
|
|
||||||
## 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.
|
||||||
@@ -217,19 +217,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)
|
|
||||||
- [vfox](https://github.com/version-fox/vfox)
|
|
||||||
|
|
||||||
## 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&columns=20" />
|
<img src="https://contributors-img.web.app/image?repo=nushell/nushell&max=500" />
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|||||||
3
README.release.txt
Normal file
3
README.release.txt
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
To use Nu plugins, use the register command to tell Nu where to find the plugin. For example:
|
||||||
|
|
||||||
|
> register -e json ./nu_plugin_query
|
||||||
29
SECURITY.md
29
SECURITY.md
@@ -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.
|
|
||||||
@@ -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`
|
|
||||||
@@ -1,541 +0,0 @@
|
|||||||
use nu_cli::{eval_source, evaluate_commands};
|
|
||||||
use nu_plugin_core::{Encoder, EncodingType};
|
|
||||||
use nu_plugin_protocol::{PluginCallResponse, PluginOutput};
|
|
||||||
use nu_protocol::{
|
|
||||||
PipelineData, Signals, Span, Spanned, Value,
|
|
||||||
engine::{EngineState, Stack},
|
|
||||||
};
|
|
||||||
use nu_std::load_standard_library;
|
|
||||||
use nu_utils::{get_default_config, get_default_env};
|
|
||||||
use std::{
|
|
||||||
fmt::Write,
|
|
||||||
hint::black_box,
|
|
||||||
rc::Rc,
|
|
||||||
sync::{Arc, atomic::AtomicBool},
|
|
||||||
};
|
|
||||||
use tango_bench::{IntoBenchmarks, benchmark_fn, tango_benchmarks, tango_main};
|
|
||||||
|
|
||||||
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();
|
|
||||||
|
|
||||||
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: impl Into<String>,
|
|
||||||
command: impl Into<String> + Clone,
|
|
||||||
stack: Stack,
|
|
||||||
engine: EngineState,
|
|
||||||
) -> impl IntoBenchmarks {
|
|
||||||
let commands = Spanned {
|
|
||||||
span: Span::unknown(),
|
|
||||||
item: command.into(),
|
|
||||||
};
|
|
||||||
[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: usize) -> String {
|
|
||||||
let mut s = String::from("let record = { ");
|
|
||||||
for i in 0..n {
|
|
||||||
write!(s, "col_{i}: {i}, ").unwrap();
|
|
||||||
}
|
|
||||||
s.push('}');
|
|
||||||
s
|
|
||||||
}
|
|
||||||
|
|
||||||
fn create_nested_record_string(depth: usize) -> 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: usize) -> 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: usize) -> impl IntoBenchmarks {
|
|
||||||
bench_command(
|
|
||||||
format!("record_create_{n}"),
|
|
||||||
create_flat_record_string(n),
|
|
||||||
Stack::new(),
|
|
||||||
setup_engine(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bench_record_flat_access(n: usize) -> 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: usize) -> 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);
|
|
||||||
bench_command(
|
|
||||||
format!("record_nested_access_{n}"),
|
|
||||||
format!("$record{nested_access} | ignore"),
|
|
||||||
stack,
|
|
||||||
engine,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bench_record_insert(n: usize, m: usize) -> impl IntoBenchmarks {
|
|
||||||
let setup_command = create_flat_record_string(n);
|
|
||||||
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
|
|
||||||
let mut insert = String::from("$record");
|
|
||||||
for i in n..(n + m) {
|
|
||||||
write!(insert, " | insert col_{i} {i}").unwrap();
|
|
||||||
}
|
|
||||||
insert.push_str(" | ignore");
|
|
||||||
bench_command(format!("record_insert_{n}_{m}"), insert, stack, engine)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bench_table_create(n: usize) -> impl IntoBenchmarks {
|
|
||||||
bench_command(
|
|
||||||
format!("table_create_{n}"),
|
|
||||||
create_example_table_nrows(n),
|
|
||||||
Stack::new(),
|
|
||||||
setup_engine(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bench_table_get(n: usize) -> 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: usize) -> 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_table_insert_row(n: usize, m: usize) -> impl IntoBenchmarks {
|
|
||||||
let setup_command = create_example_table_nrows(n);
|
|
||||||
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
|
|
||||||
let mut insert = String::from("$table");
|
|
||||||
for i in n..(n + m) {
|
|
||||||
write!(insert, " | insert {i} {{ foo: 0, bar: 1, baz: {i} }}").unwrap();
|
|
||||||
}
|
|
||||||
insert.push_str(" | ignore");
|
|
||||||
bench_command(format!("table_insert_row_{n}_{m}"), insert, stack, engine)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bench_table_insert_col(n: usize, m: usize) -> impl IntoBenchmarks {
|
|
||||||
let setup_command = create_example_table_nrows(n);
|
|
||||||
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
|
|
||||||
let mut insert = String::from("$table");
|
|
||||||
for i in 0..m {
|
|
||||||
write!(insert, " | insert col_{i} {i}").unwrap();
|
|
||||||
}
|
|
||||||
insert.push_str(" | ignore");
|
|
||||||
bench_command(format!("table_insert_col_{n}_{m}"), insert, stack, engine)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bench_eval_interleave(n: usize) -> 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: usize) -> 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: usize) -> 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: usize) -> 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: usize) -> impl IntoBenchmarks {
|
|
||||||
let engine = setup_engine();
|
|
||||||
let stack = Stack::new();
|
|
||||||
bench_command(
|
|
||||||
format!("eval_par_each_{n}"),
|
|
||||||
format!("(1..{n}) | par-each -t 2 {{|_| 1 }} | ignore"),
|
|
||||||
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),
|
|
||||||
bench_record_insert(1, 1),
|
|
||||||
bench_record_insert(10, 1),
|
|
||||||
bench_record_insert(100, 1),
|
|
||||||
bench_record_insert(1000, 1),
|
|
||||||
bench_record_insert(1, 10),
|
|
||||||
bench_record_insert(10, 10),
|
|
||||||
bench_record_insert(100, 10),
|
|
||||||
bench_record_insert(1000, 10),
|
|
||||||
// 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),
|
|
||||||
bench_table_insert_row(1, 1),
|
|
||||||
bench_table_insert_row(10, 1),
|
|
||||||
bench_table_insert_row(100, 1),
|
|
||||||
bench_table_insert_row(1000, 1),
|
|
||||||
bench_table_insert_row(1, 10),
|
|
||||||
bench_table_insert_row(10, 10),
|
|
||||||
bench_table_insert_row(100, 10),
|
|
||||||
bench_table_insert_row(1000, 10),
|
|
||||||
bench_table_insert_col(1, 1),
|
|
||||||
bench_table_insert_col(10, 1),
|
|
||||||
bench_table_insert_col(100, 1),
|
|
||||||
bench_table_insert_col(1000, 1),
|
|
||||||
bench_table_insert_col(1, 10),
|
|
||||||
bench_table_insert_col(10, 10),
|
|
||||||
bench_table_insert_col(100, 10),
|
|
||||||
bench_table_insert_col(1000, 10),
|
|
||||||
// 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!();
|
|
||||||
@@ -1,12 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/bin/sh
|
||||||
|
|
||||||
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 --features=extra and all the plugins"
|
||||||
echo "---------------------------------------------------------------"
|
echo "---------------------------------------------------------------"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
@@ -15,22 +10,14 @@ NU_PLUGINS=(
|
|||||||
'nu_plugin_gstat'
|
'nu_plugin_gstat'
|
||||||
'nu_plugin_inc'
|
'nu_plugin_inc'
|
||||||
'nu_plugin_query'
|
'nu_plugin_query'
|
||||||
'nu_plugin_custom_values'
|
|
||||||
'nu_plugin_polars'
|
|
||||||
)
|
)
|
||||||
|
|
||||||
echo "Building nushell"
|
echo "Building nushell"
|
||||||
(
|
cargo build --features=extra
|
||||||
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
|
||||||
32
build-all-windows.cmd
Normal file
32
build-all-windows.cmd
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
@echo off
|
||||||
|
@echo -------------------------------------------------------------------
|
||||||
|
@echo Building nushell (nu.exe) with --features=extra and all the plugins
|
||||||
|
@echo -------------------------------------------------------------------
|
||||||
|
@echo.
|
||||||
|
|
||||||
|
echo Building nushell.exe
|
||||||
|
cargo build --features=extra
|
||||||
|
@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 ..\..
|
||||||
22
build-all.nu
Normal file
22
build-all.nu
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
echo '-------------------------------------------------------------------'
|
||||||
|
echo 'Building nushell (nu) with --features=extra and all the plugins'
|
||||||
|
echo '-------------------------------------------------------------------'
|
||||||
|
|
||||||
|
echo $'(char nl)Building nushell'
|
||||||
|
echo '----------------------------'
|
||||||
|
cargo build --features=extra
|
||||||
|
|
||||||
|
let plugins = [
|
||||||
|
nu_plugin_inc,
|
||||||
|
nu_plugin_gstat,
|
||||||
|
nu_plugin_query,
|
||||||
|
nu_plugin_example,
|
||||||
|
]
|
||||||
|
|
||||||
|
for plugin in $plugins {
|
||||||
|
$'(char nl)Building ($plugin)'
|
||||||
|
'----------------------------'
|
||||||
|
cd $'crates/($plugin)'
|
||||||
|
cargo build
|
||||||
|
ignore
|
||||||
|
}
|
||||||
13
build.rs
Normal file
13
build.rs
Normal 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() {}
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
[[disallowed-types]]
|
|
||||||
path = "std::time::Instant"
|
|
||||||
reason = "WASM panics if used, use `web_time::Instant` instead"
|
|
||||||
@@ -1,54 +1,36 @@
|
|||||||
[package]
|
[package]
|
||||||
authors = ["The Nushell Project Developers"]
|
authors = ["The Nushell Project Developers"]
|
||||||
description = "CLI-related functionality for Nushell"
|
description = "CLI-related functionality for Nushell"
|
||||||
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cli"
|
edition = "2021"
|
||||||
edition = "2024"
|
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
name = "nu-cli"
|
name = "nu-cli"
|
||||||
version = "0.106.0"
|
version = "0.66.2"
|
||||||
|
|
||||||
[lib]
|
|
||||||
bench = false
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.106.0" }
|
nu-test-support = { path="../nu-test-support", version = "0.66.2" }
|
||||||
nu-command = { path = "../nu-command", version = "0.106.0" }
|
nu-command = { path = "../nu-command", version = "0.66.2" }
|
||||||
nu-std = { path = "../nu-std", version = "0.106.0" }
|
rstest = "0.15.0"
|
||||||
nu-test-support = { path = "../nu-test-support", version = "0.106.0" }
|
|
||||||
rstest = { workspace = true, default-features = false }
|
|
||||||
tempfile = { workspace = true }
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
nu-cmd-base = { path = "../nu-cmd-base", version = "0.106.0" }
|
nu-engine = { path = "../nu-engine", version = "0.66.2" }
|
||||||
nu-engine = { path = "../nu-engine", version = "0.106.0", features = ["os"] }
|
nu-path = { path = "../nu-path", version = "0.66.2" }
|
||||||
nu-glob = { path = "../nu-glob", version = "0.106.0" }
|
nu-parser = { path = "../nu-parser", version = "0.66.2" }
|
||||||
nu-path = { path = "../nu-path", version = "0.106.0" }
|
nu-protocol = { path = "../nu-protocol", version = "0.66.2" }
|
||||||
nu-parser = { path = "../nu-parser", version = "0.106.0" }
|
nu-utils = { path = "../nu-utils", version = "0.66.2" }
|
||||||
nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.106.0", optional = true }
|
nu-ansi-term = "0.46.0"
|
||||||
nu-protocol = { path = "../nu-protocol", version = "0.106.0", features = ["os"] }
|
nu-color-config = { path = "../nu-color-config", version = "0.66.2" }
|
||||||
nu-utils = { path = "../nu-utils", version = "0.106.0" }
|
reedline = { version = "0.9.0", features = ["bashisms", "sqlite"]}
|
||||||
nu-color-config = { path = "../nu-color-config", version = "0.106.0" }
|
crossterm = "0.23.0"
|
||||||
nu-ansi-term = { workspace = true }
|
miette = { version = "5.1.0", features = ["fancy"] }
|
||||||
reedline = { workspace = true, features = ["bashisms", "sqlite"] }
|
thiserror = "1.0.31"
|
||||||
|
fuzzy-matcher = "0.3.7"
|
||||||
|
|
||||||
chrono = { default-features = false, features = ["std"], workspace = true }
|
chrono = "0.4.19"
|
||||||
crossterm = { workspace = true }
|
is_executable = "1.0.1"
|
||||||
fancy-regex = { workspace = true }
|
lazy_static = "1.4.0"
|
||||||
is_executable = { workspace = true }
|
log = "0.4"
|
||||||
log = { workspace = true }
|
regex = "1.5.4"
|
||||||
lscolors = { workspace = true, default-features = false, features = ["nu-ansi-term"] }
|
sysinfo = "0.24.1"
|
||||||
miette = { workspace = true, features = ["fancy-no-backtrace"] }
|
|
||||||
nucleo-matcher = { workspace = true }
|
|
||||||
percent-encoding = { workspace = true }
|
|
||||||
sysinfo = { workspace = true }
|
|
||||||
strum = { workspace = true }
|
|
||||||
unicode-segmentation = { workspace = true }
|
|
||||||
uuid = { workspace = true, features = ["v4"] }
|
|
||||||
which = { workspace = true }
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
plugin = ["nu-plugin-engine"]
|
plugin = []
|
||||||
system-clipboard = ["reedline/system_clipboard"]
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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.
|
|
||||||
76
crates/nu-cli/src/commands.rs
Normal file
76
crates/nu-cli/src/commands.rs
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
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,
|
||||||
|
is_perf_true: bool,
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if is_perf_true {
|
||||||
|
info!("evaluate {}:{}:{}", file!(), line!(), column!());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(exit_code)
|
||||||
|
}
|
||||||
@@ -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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
use nu_engine::command_prelude::*;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct CommandlineEdit;
|
|
||||||
|
|
||||||
impl Command for CommandlineEdit {
|
|
||||||
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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
use nu_engine::command_prelude::*;
|
|
||||||
use unicode_segmentation::UnicodeSegmentation;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct CommandlineGetCursor;
|
|
||||||
|
|
||||||
impl Command for CommandlineGetCursor {
|
|
||||||
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![],
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
mod commandline_;
|
|
||||||
mod edit;
|
|
||||||
mod get_cursor;
|
|
||||||
mod set_cursor;
|
|
||||||
|
|
||||||
pub use commandline_::Commandline;
|
|
||||||
pub use edit::CommandlineEdit;
|
|
||||||
pub use get_cursor::CommandlineGetCursor;
|
|
||||||
pub use set_cursor::CommandlineSetCursor;
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
use nu_engine::command_prelude::*;
|
|
||||||
|
|
||||||
use unicode_segmentation::UnicodeSegmentation;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct CommandlineSetCursor;
|
|
||||||
|
|
||||||
impl Command for CommandlineSetCursor {
|
|
||||||
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![],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +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,
|
|
||||||
HistoryImport,
|
|
||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
// Each const is named after a HistoryItem field, and the value is the field name to be displayed to
|
|
||||||
// the user (or accept during import).
|
|
||||||
pub const COMMAND_LINE: &str = "command";
|
|
||||||
pub const START_TIMESTAMP: &str = "start_timestamp";
|
|
||||||
pub const HOSTNAME: &str = "hostname";
|
|
||||||
pub const CWD: &str = "cwd";
|
|
||||||
pub const EXIT_STATUS: &str = "exit_status";
|
|
||||||
pub const DURATION: &str = "duration";
|
|
||||||
pub const SESSION_ID: &str = "session_id";
|
|
||||||
@@ -1,206 +0,0 @@
|
|||||||
use nu_engine::command_prelude::*;
|
|
||||||
use nu_protocol::{
|
|
||||||
HistoryFileFormat,
|
|
||||||
shell_error::{self, io::IoError},
|
|
||||||
};
|
|
||||||
use reedline::{
|
|
||||||
FileBackedHistory, History as ReedlineHistory, HistoryItem, SearchDirection, SearchQuery,
|
|
||||||
SqliteBackedHistory,
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::fields;
|
|
||||||
|
|
||||||
#[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! {
|
|
||||||
fields::COMMAND_LINE => Value::string(entry.command_line, head),
|
|
||||||
// TODO: This name is inconsistent with create_history_record.
|
|
||||||
"index" => Value::int(idx as i64, head),
|
|
||||||
},
|
|
||||||
head,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.ok_or(IoError::new(
|
|
||||||
shell_error::io::ErrorKind::FileNotFound,
|
|
||||||
head,
|
|
||||||
history_path,
|
|
||||||
))?
|
|
||||||
.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_sqlite_history_record(idx, entry, long, head)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.ok_or(IoError::new(
|
|
||||||
shell_error::io::ErrorKind::FileNotFound,
|
|
||||||
head,
|
|
||||||
history_path,
|
|
||||||
))?
|
|
||||||
.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_sqlite_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::date(
|
|
||||||
entry.start_timestamp.unwrap_or_default().fixed_offset(),
|
|
||||||
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,
|
|
||||||
fields::START_TIMESTAMP => start_timestamp_value,
|
|
||||||
fields::COMMAND_LINE => command_value,
|
|
||||||
fields::SESSION_ID => session_id_value,
|
|
||||||
fields::HOSTNAME => hostname_value,
|
|
||||||
fields::CWD => cwd_value,
|
|
||||||
fields::DURATION => duration_value,
|
|
||||||
fields::EXIT_STATUS => exit_status_value,
|
|
||||||
"idx" => index_value,
|
|
||||||
},
|
|
||||||
head,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Value::record(
|
|
||||||
record! {
|
|
||||||
fields::START_TIMESTAMP => start_timestamp_value,
|
|
||||||
fields::COMMAND_LINE => command_value,
|
|
||||||
fields::CWD => cwd_value,
|
|
||||||
fields::DURATION => duration_value,
|
|
||||||
fields::EXIT_STATUS => exit_status_value,
|
|
||||||
},
|
|
||||||
head,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,440 +0,0 @@
|
|||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use nu_engine::command_prelude::*;
|
|
||||||
use nu_protocol::{
|
|
||||||
HistoryFileFormat,
|
|
||||||
shell_error::{self, io::IoError},
|
|
||||||
};
|
|
||||||
|
|
||||||
use reedline::{
|
|
||||||
FileBackedHistory, History, HistoryItem, ReedlineError, SearchQuery, SqliteBackedHistory,
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::fields;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct HistoryImport;
|
|
||||||
|
|
||||||
impl Command for HistoryImport {
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"history import"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn description(&self) -> &str {
|
|
||||||
"Import command line history."
|
|
||||||
}
|
|
||||||
|
|
||||||
fn extra_description(&self) -> &str {
|
|
||||||
r#"Can import history from input, either successive command lines or more detailed records. If providing records, available fields are:
|
|
||||||
command, start_timestamp, hostname, cwd, duration, exit_status.
|
|
||||||
|
|
||||||
If no input is provided, will import all history items from existing history in the other format: if current history is stored in sqlite, it will store it in plain text and vice versa.
|
|
||||||
|
|
||||||
Note that history item IDs are ignored when importing from file."#
|
|
||||||
}
|
|
||||||
|
|
||||||
fn signature(&self) -> nu_protocol::Signature {
|
|
||||||
Signature::build("history import")
|
|
||||||
.category(Category::History)
|
|
||||||
.input_output_types(vec![
|
|
||||||
(Type::Nothing, Type::Nothing),
|
|
||||||
(Type::String, Type::Nothing),
|
|
||||||
(Type::List(Box::new(Type::String)), Type::Nothing),
|
|
||||||
(Type::table(), Type::Nothing),
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
fn examples(&self) -> Vec<Example> {
|
|
||||||
vec![
|
|
||||||
Example {
|
|
||||||
example: "history import",
|
|
||||||
description: "Append all items from history in the other format to the current history",
|
|
||||||
result: None,
|
|
||||||
},
|
|
||||||
Example {
|
|
||||||
example: "echo foo | history import",
|
|
||||||
description: "Append `foo` to the current history",
|
|
||||||
result: None,
|
|
||||||
},
|
|
||||||
Example {
|
|
||||||
example: "[[ command cwd ]; [ foo /home ]] | history import",
|
|
||||||
description: "Append `foo` ran from `/home` to the current history",
|
|
||||||
result: None,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(
|
|
||||||
&self,
|
|
||||||
engine_state: &EngineState,
|
|
||||||
_stack: &mut Stack,
|
|
||||||
call: &Call,
|
|
||||||
input: PipelineData,
|
|
||||||
) -> Result<PipelineData, ShellError> {
|
|
||||||
let span = call.head;
|
|
||||||
let ok = Ok(Value::nothing(call.head).into_pipeline_data());
|
|
||||||
|
|
||||||
let Some(history) = engine_state.history_config() else {
|
|
||||||
return ok;
|
|
||||||
};
|
|
||||||
let Some(current_history_path) = history.file_path() else {
|
|
||||||
return Err(ShellError::ConfigDirNotFound { span: span.into() });
|
|
||||||
};
|
|
||||||
if let Some(bak_path) = backup(¤t_history_path, span)? {
|
|
||||||
println!("Backed history to {}", bak_path.display());
|
|
||||||
}
|
|
||||||
match input {
|
|
||||||
PipelineData::Empty => {
|
|
||||||
let other_format = match history.file_format {
|
|
||||||
HistoryFileFormat::Sqlite => HistoryFileFormat::Plaintext,
|
|
||||||
HistoryFileFormat::Plaintext => HistoryFileFormat::Sqlite,
|
|
||||||
};
|
|
||||||
let src = new_backend(other_format, None)?;
|
|
||||||
let mut dst = new_backend(history.file_format, Some(current_history_path))?;
|
|
||||||
let items = src
|
|
||||||
.search(SearchQuery::everything(
|
|
||||||
reedline::SearchDirection::Forward,
|
|
||||||
None,
|
|
||||||
))
|
|
||||||
.map_err(error_from_reedline)?
|
|
||||||
.into_iter()
|
|
||||||
.map(Ok);
|
|
||||||
import(dst.as_mut(), items)
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
let input = input.into_iter().map(item_from_value);
|
|
||||||
import(
|
|
||||||
new_backend(history.file_format, Some(current_history_path))?.as_mut(),
|
|
||||||
input,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}?;
|
|
||||||
|
|
||||||
ok
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn new_backend(
|
|
||||||
format: HistoryFileFormat,
|
|
||||||
path: Option<PathBuf>,
|
|
||||||
) -> Result<Box<dyn History>, ShellError> {
|
|
||||||
let path = match path {
|
|
||||||
Some(path) => path,
|
|
||||||
None => {
|
|
||||||
let Some(mut path) = nu_path::nu_config_dir() else {
|
|
||||||
return Err(ShellError::ConfigDirNotFound { span: None });
|
|
||||||
};
|
|
||||||
path.push(format.default_file_name());
|
|
||||||
path.into_std_path_buf()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fn map(
|
|
||||||
result: Result<impl History + 'static, ReedlineError>,
|
|
||||||
) -> Result<Box<dyn History>, ShellError> {
|
|
||||||
result
|
|
||||||
.map(|x| Box::new(x) as Box<dyn History>)
|
|
||||||
.map_err(error_from_reedline)
|
|
||||||
}
|
|
||||||
match format {
|
|
||||||
// Use a reasonably large value for maximum capacity.
|
|
||||||
HistoryFileFormat::Plaintext => map(FileBackedHistory::with_file(0xfffffff, path)),
|
|
||||||
HistoryFileFormat::Sqlite => map(SqliteBackedHistory::with_file(path, None, None)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn import(
|
|
||||||
dst: &mut dyn History,
|
|
||||||
src: impl Iterator<Item = Result<HistoryItem, ShellError>>,
|
|
||||||
) -> Result<(), ShellError> {
|
|
||||||
for item in src {
|
|
||||||
let mut item = item?;
|
|
||||||
item.id = None;
|
|
||||||
dst.save(item).map_err(error_from_reedline)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn error_from_reedline(e: ReedlineError) -> ShellError {
|
|
||||||
// TODO: Should we add a new ShellError variant?
|
|
||||||
ShellError::GenericError {
|
|
||||||
error: "Reedline error".to_owned(),
|
|
||||||
msg: format!("{e}"),
|
|
||||||
span: None,
|
|
||||||
help: None,
|
|
||||||
inner: Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn item_from_value(v: Value) -> Result<HistoryItem, ShellError> {
|
|
||||||
let span = v.span();
|
|
||||||
match v {
|
|
||||||
Value::Record { val, .. } => item_from_record(val.into_owned(), span),
|
|
||||||
Value::String { val, .. } => Ok(HistoryItem {
|
|
||||||
command_line: val,
|
|
||||||
id: None,
|
|
||||||
start_timestamp: None,
|
|
||||||
session_id: None,
|
|
||||||
hostname: None,
|
|
||||||
cwd: None,
|
|
||||||
duration: None,
|
|
||||||
exit_status: None,
|
|
||||||
more_info: None,
|
|
||||||
}),
|
|
||||||
_ => Err(ShellError::UnsupportedInput {
|
|
||||||
msg: "Only list and record inputs are supported".to_owned(),
|
|
||||||
input: v.get_type().to_string(),
|
|
||||||
msg_span: span,
|
|
||||||
input_span: span,
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn item_from_record(mut rec: Record, span: Span) -> Result<HistoryItem, ShellError> {
|
|
||||||
let cmd = match rec.remove(fields::COMMAND_LINE) {
|
|
||||||
Some(v) => v.as_str()?.to_owned(),
|
|
||||||
None => {
|
|
||||||
return Err(ShellError::TypeMismatch {
|
|
||||||
err_message: format!("missing column: {}", fields::COMMAND_LINE),
|
|
||||||
span,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fn get<T>(
|
|
||||||
rec: &mut Record,
|
|
||||||
field: &'static str,
|
|
||||||
f: impl FnOnce(Value) -> Result<T, ShellError>,
|
|
||||||
) -> Result<Option<T>, ShellError> {
|
|
||||||
rec.remove(field).map(f).transpose()
|
|
||||||
}
|
|
||||||
|
|
||||||
let rec = &mut rec;
|
|
||||||
let item = HistoryItem {
|
|
||||||
command_line: cmd,
|
|
||||||
id: None,
|
|
||||||
start_timestamp: get(rec, fields::START_TIMESTAMP, |v| Ok(v.as_date()?.to_utc()))?,
|
|
||||||
hostname: get(rec, fields::HOSTNAME, |v| Ok(v.as_str()?.to_owned()))?,
|
|
||||||
cwd: get(rec, fields::CWD, |v| Ok(v.as_str()?.to_owned()))?,
|
|
||||||
exit_status: get(rec, fields::EXIT_STATUS, |v| v.as_int())?,
|
|
||||||
duration: get(rec, fields::DURATION, |v| duration_from_value(v, span))?,
|
|
||||||
more_info: None,
|
|
||||||
// TODO: Currently reedline doesn't let you create session IDs.
|
|
||||||
session_id: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
if !rec.is_empty() {
|
|
||||||
let cols = rec.columns().map(|s| s.as_str()).collect::<Vec<_>>();
|
|
||||||
return Err(ShellError::TypeMismatch {
|
|
||||||
err_message: format!("unsupported column names: {}", cols.join(", ")),
|
|
||||||
span,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(item)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn duration_from_value(v: Value, span: Span) -> Result<std::time::Duration, ShellError> {
|
|
||||||
chrono::Duration::nanoseconds(v.as_duration()?)
|
|
||||||
.to_std()
|
|
||||||
.map_err(|_| ShellError::NeedsPositiveValue { span })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_backup_path(path: &Path, span: Span) -> Result<PathBuf, ShellError> {
|
|
||||||
let Ok(mut bak_path) = path.to_path_buf().into_os_string().into_string() else {
|
|
||||||
// This isn't fundamentally problem, but trying to work with OsString is a nightmare.
|
|
||||||
return Err(ShellError::GenericError {
|
|
||||||
error: "History path not UTF-8".to_string(),
|
|
||||||
msg: "History path must be representable as UTF-8".to_string(),
|
|
||||||
span: Some(span),
|
|
||||||
help: None,
|
|
||||||
inner: vec![],
|
|
||||||
});
|
|
||||||
};
|
|
||||||
bak_path.push_str(".bak");
|
|
||||||
if !Path::new(&bak_path).exists() {
|
|
||||||
return Ok(bak_path.into());
|
|
||||||
}
|
|
||||||
let base_len = bak_path.len();
|
|
||||||
for i in 1..100 {
|
|
||||||
use std::fmt::Write;
|
|
||||||
bak_path.truncate(base_len);
|
|
||||||
write!(&mut bak_path, ".{i}").unwrap();
|
|
||||||
if !Path::new(&bak_path).exists() {
|
|
||||||
return Ok(PathBuf::from(bak_path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(ShellError::GenericError {
|
|
||||||
error: "Too many backup files".to_string(),
|
|
||||||
msg: "Found too many existing backup files".to_string(),
|
|
||||||
span: Some(span),
|
|
||||||
help: None,
|
|
||||||
inner: vec![],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn backup(path: &Path, span: Span) -> Result<Option<PathBuf>, ShellError> {
|
|
||||||
match path.metadata() {
|
|
||||||
Ok(md) if md.is_file() => (),
|
|
||||||
Ok(_) => {
|
|
||||||
return Err(IoError::new_with_additional_context(
|
|
||||||
shell_error::io::ErrorKind::NotAFile,
|
|
||||||
span,
|
|
||||||
PathBuf::from(path),
|
|
||||||
"history path exists but is not a file",
|
|
||||||
)
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
|
||||||
Err(e) => {
|
|
||||||
return Err(IoError::new_internal(
|
|
||||||
e,
|
|
||||||
"Could not get metadata",
|
|
||||||
nu_protocol::location!(),
|
|
||||||
)
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let bak_path = find_backup_path(path, span)?;
|
|
||||||
std::fs::copy(path, &bak_path).map_err(|err| {
|
|
||||||
IoError::new_internal(
|
|
||||||
err.not_found_as(NotFound::File),
|
|
||||||
"Could not copy backup",
|
|
||||||
nu_protocol::location!(),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
Ok(Some(bak_path))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use chrono::DateTime;
|
|
||||||
use rstest::rstest;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_item_from_value_string() -> Result<(), ShellError> {
|
|
||||||
let item = item_from_value(Value::string("foo", Span::unknown()))?;
|
|
||||||
assert_eq!(
|
|
||||||
item,
|
|
||||||
HistoryItem {
|
|
||||||
command_line: "foo".to_string(),
|
|
||||||
id: None,
|
|
||||||
start_timestamp: None,
|
|
||||||
session_id: None,
|
|
||||||
hostname: None,
|
|
||||||
cwd: None,
|
|
||||||
duration: None,
|
|
||||||
exit_status: None,
|
|
||||||
more_info: None
|
|
||||||
}
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_item_from_value_record() {
|
|
||||||
let span = Span::unknown();
|
|
||||||
let rec = new_record(&[
|
|
||||||
("command", Value::string("foo", span)),
|
|
||||||
(
|
|
||||||
"start_timestamp",
|
|
||||||
Value::date(
|
|
||||||
DateTime::parse_from_rfc3339("1996-12-19T16:39:57-08:00").unwrap(),
|
|
||||||
span,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
("hostname", Value::string("localhost", span)),
|
|
||||||
("cwd", Value::string("/home/test", span)),
|
|
||||||
("duration", Value::duration(100_000_000, span)),
|
|
||||||
("exit_status", Value::int(42, span)),
|
|
||||||
]);
|
|
||||||
let item = item_from_value(rec).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
item,
|
|
||||||
HistoryItem {
|
|
||||||
command_line: "foo".to_string(),
|
|
||||||
id: None,
|
|
||||||
start_timestamp: Some(
|
|
||||||
DateTime::parse_from_rfc3339("1996-12-19T16:39:57-08:00")
|
|
||||||
.unwrap()
|
|
||||||
.to_utc()
|
|
||||||
),
|
|
||||||
hostname: Some("localhost".to_string()),
|
|
||||||
cwd: Some("/home/test".to_string()),
|
|
||||||
duration: Some(std::time::Duration::from_nanos(100_000_000)),
|
|
||||||
exit_status: Some(42),
|
|
||||||
|
|
||||||
session_id: None,
|
|
||||||
more_info: None
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_item_from_value_record_extra_field() {
|
|
||||||
let span = Span::unknown();
|
|
||||||
let rec = new_record(&[
|
|
||||||
("command_line", Value::string("foo", span)),
|
|
||||||
("id_nonexistent", Value::int(1, span)),
|
|
||||||
]);
|
|
||||||
assert!(item_from_value(rec).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_item_from_value_record_bad_type() {
|
|
||||||
let span = Span::unknown();
|
|
||||||
let rec = new_record(&[
|
|
||||||
("command_line", Value::string("foo", span)),
|
|
||||||
("id", Value::string("one".to_string(), span)),
|
|
||||||
]);
|
|
||||||
assert!(item_from_value(rec).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn new_record(rec: &[(&'static str, Value)]) -> Value {
|
|
||||||
let span = Span::unknown();
|
|
||||||
let rec = Record::from_raw_cols_vals(
|
|
||||||
rec.iter().map(|(col, _)| col.to_string()).collect(),
|
|
||||||
rec.iter().map(|(_, val)| val.clone()).collect(),
|
|
||||||
span,
|
|
||||||
span,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
Value::record(rec, span)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[rstest]
|
|
||||||
#[case::no_backup(&["history.dat"], "history.dat.bak")]
|
|
||||||
#[case::backup_exists(&["history.dat", "history.dat.bak"], "history.dat.bak.1")]
|
|
||||||
#[case::multiple_backups_exists( &["history.dat", "history.dat.bak", "history.dat.bak.1"], "history.dat.bak.2")]
|
|
||||||
fn test_find_backup_path(#[case] existing: &[&str], #[case] want: &str) {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
for name in existing {
|
|
||||||
std::fs::File::create_new(dir.path().join(name)).unwrap();
|
|
||||||
}
|
|
||||||
let got = find_backup_path(&dir.path().join("history.dat"), Span::test_data()).unwrap();
|
|
||||||
assert_eq!(got, dir.path().join(want))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_backup() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let mut history = std::fs::File::create_new(dir.path().join("history.dat")).unwrap();
|
|
||||||
use std::io::Write;
|
|
||||||
write!(&mut history, "123").unwrap();
|
|
||||||
let want_bak_path = dir.path().join("history.dat.bak");
|
|
||||||
assert_eq!(
|
|
||||||
backup(&dir.path().join("history.dat"), Span::test_data()),
|
|
||||||
Ok(Some(want_bak_path.clone()))
|
|
||||||
);
|
|
||||||
let got_data = String::from_utf8(std::fs::read(want_bak_path).unwrap()).unwrap();
|
|
||||||
assert_eq!(got_data, "123");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_backup_no_file() {
|
|
||||||
let dir = tempfile::tempdir().unwrap();
|
|
||||||
let bak_path = backup(&dir.path().join("history.dat"), Span::test_data()).unwrap();
|
|
||||||
assert!(bak_path.is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
use nu_engine::command_prelude::*;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct HistorySession;
|
|
||||||
|
|
||||||
impl Command for HistorySession {
|
|
||||||
fn name(&self) -> &str {
|
|
||||||
"history session"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn description(&self) -> &str {
|
|
||||||
"Get the command history session."
|
|
||||||
}
|
|
||||||
|
|
||||||
fn signature(&self) -> nu_protocol::Signature {
|
|
||||||
Signature::build("history session")
|
|
||||||
.category(Category::History)
|
|
||||||
.input_output_types(vec![(Type::Nothing, Type::Int)])
|
|
||||||
}
|
|
||||||
|
|
||||||
fn examples(&self) -> Vec<Example> {
|
|
||||||
vec![Example {
|
|
||||||
example: "history session",
|
|
||||||
description: "Get current history session",
|
|
||||||
result: None,
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(
|
|
||||||
&self,
|
|
||||||
engine_state: &EngineState,
|
|
||||||
_stack: &mut Stack,
|
|
||||||
call: &Call,
|
|
||||||
_input: PipelineData,
|
|
||||||
) -> Result<PipelineData, ShellError> {
|
|
||||||
Ok(Value::int(engine_state.history_session_id, call.head).into_pipeline_data())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
mod fields;
|
|
||||||
mod history_;
|
|
||||||
mod history_import;
|
|
||||||
mod history_session;
|
|
||||||
|
|
||||||
pub use history_::History;
|
|
||||||
pub use history_import::HistoryImport;
|
|
||||||
pub use history_session::HistorySession;
|
|
||||||
@@ -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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,200 +0,0 @@
|
|||||||
use crossterm::{
|
|
||||||
QueueableCommand, event::Event, event::KeyCode, event::KeyEvent, execute, terminal,
|
|
||||||
};
|
|
||||||
use nu_engine::command_prelude::*;
|
|
||||||
use nu_protocol::shell_error::io::IoError;
|
|
||||||
use std::io::{Write, stdout};
|
|
||||||
|
|
||||||
#[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().map_err(|err| {
|
|
||||||
IoError::new_internal(
|
|
||||||
err,
|
|
||||||
"Could not disable raw mode",
|
|
||||||
nu_protocol::location!(),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
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().map_err(|err| {
|
|
||||||
IoError::new_internal(err, "Could not flush stdout", nu_protocol::location!())
|
|
||||||
})?;
|
|
||||||
terminal::enable_raw_mode().map_err(|err| {
|
|
||||||
IoError::new_internal(err, "Could not enable raw mode", nu_protocol::location!())
|
|
||||||
})?;
|
|
||||||
|
|
||||||
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().map_err(|err| {
|
|
||||||
IoError::new_internal(err, "Could not read event", nu_protocol::location!())
|
|
||||||
})?;
|
|
||||||
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)).map_err(|err| {
|
|
||||||
IoError::new_internal(
|
|
||||||
err,
|
|
||||||
"Could not print output record",
|
|
||||||
nu_protocol::location!(),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
stdout
|
|
||||||
.queue(crossterm::style::Print("\r\n"))
|
|
||||||
.map_err(|err| {
|
|
||||||
IoError::new_internal(err, "Could not print linebreak", nu_protocol::location!())
|
|
||||||
})?;
|
|
||||||
stdout.flush().map_err(|err| {
|
|
||||||
IoError::new_internal(err, "Could not flush", nu_protocol::location!())
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
|
|
||||||
if config.use_kitty_protocol {
|
|
||||||
let _ = execute!(
|
|
||||||
std::io::stdout(),
|
|
||||||
crossterm::event::PopKeyboardEnhancementFlags
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
terminal::disable_raw_mode().map_err(|err| {
|
|
||||||
IoError::new_internal(err, "Could not disable raw mode", nu_protocol::location!())
|
|
||||||
})?;
|
|
||||||
|
|
||||||
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()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
use super::{SemanticSuggestion, completion_options::NuMatcher};
|
|
||||||
use crate::{
|
|
||||||
SuggestionKind,
|
|
||||||
completions::{Completer, CompletionOptions},
|
|
||||||
};
|
|
||||||
use nu_protocol::{
|
|
||||||
Span,
|
|
||||||
engine::{Stack, StateWorkingSet},
|
|
||||||
};
|
|
||||||
use reedline::Suggestion;
|
|
||||||
|
|
||||||
pub struct AttributeCompletion;
|
|
||||||
pub struct AttributableCompletion;
|
|
||||||
|
|
||||||
impl Completer for AttributeCompletion {
|
|
||||||
fn fetch(
|
|
||||||
&mut self,
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
_stack: &Stack,
|
|
||||||
prefix: impl AsRef<str>,
|
|
||||||
span: Span,
|
|
||||||
offset: usize,
|
|
||||||
options: &CompletionOptions,
|
|
||||||
) -> Vec<SemanticSuggestion> {
|
|
||||||
let mut matcher = NuMatcher::new(prefix, options);
|
|
||||||
|
|
||||||
let attr_commands =
|
|
||||||
working_set.find_commands_by_predicate(|s| s.starts_with(b"attr "), true);
|
|
||||||
|
|
||||||
for (decl_id, name, desc, ty) in attr_commands {
|
|
||||||
let name = name.strip_prefix(b"attr ").unwrap_or(&name);
|
|
||||||
matcher.add_semantic_suggestion(SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value: String::from_utf8_lossy(name).into_owned(),
|
|
||||||
description: desc,
|
|
||||||
span: reedline::Span {
|
|
||||||
start: span.start - offset,
|
|
||||||
end: span.end - offset,
|
|
||||||
},
|
|
||||||
append_whitespace: false,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
kind: Some(SuggestionKind::Command(ty, Some(decl_id))),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
matcher.results()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Completer for AttributableCompletion {
|
|
||||||
fn fetch(
|
|
||||||
&mut self,
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
_stack: &Stack,
|
|
||||||
prefix: impl AsRef<str>,
|
|
||||||
span: Span,
|
|
||||||
offset: usize,
|
|
||||||
options: &CompletionOptions,
|
|
||||||
) -> Vec<SemanticSuggestion> {
|
|
||||||
let mut matcher = NuMatcher::new(prefix, options);
|
|
||||||
|
|
||||||
for s in ["def", "extern", "export def", "export extern"] {
|
|
||||||
let decl_id = working_set
|
|
||||||
.find_decl(s.as_bytes())
|
|
||||||
.expect("internal error, builtin declaration not found");
|
|
||||||
let cmd = working_set.get_decl(decl_id);
|
|
||||||
matcher.add_semantic_suggestion(SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value: cmd.name().into(),
|
|
||||||
description: Some(cmd.description().into()),
|
|
||||||
span: reedline::Span {
|
|
||||||
start: span.start - offset,
|
|
||||||
end: span.end - offset,
|
|
||||||
},
|
|
||||||
append_whitespace: false,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
kind: Some(SuggestionKind::Command(cmd.command_type(), None)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
matcher.results()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +1,43 @@
|
|||||||
use crate::completions::CompletionOptions;
|
use crate::completions::{CompletionOptions, SortBy};
|
||||||
use nu_protocol::{
|
use nu_protocol::{engine::StateWorkingSet, levenshtein_distance, Span};
|
||||||
DeclId, Span,
|
|
||||||
engine::{Stack, StateWorkingSet},
|
|
||||||
};
|
|
||||||
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: impl AsRef<str>,
|
|
||||||
span: Span,
|
span: Span,
|
||||||
offset: usize,
|
offset: 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, Option<DeclId>),
|
|
||||||
Value(nu_protocol::Type),
|
|
||||||
CellPath,
|
|
||||||
Directory,
|
|
||||||
File,
|
|
||||||
Flag,
|
|
||||||
Module,
|
|
||||||
Operator,
|
|
||||||
Variable,
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,153 +0,0 @@
|
|||||||
use std::borrow::Cow;
|
|
||||||
|
|
||||||
use crate::completions::{Completer, CompletionOptions, SemanticSuggestion, SuggestionKind};
|
|
||||||
use nu_engine::{column::get_columns, eval_variable};
|
|
||||||
use nu_protocol::{
|
|
||||||
ShellError, Span, Value,
|
|
||||||
ast::{Expr, Expression, FullCellPath, PathMember},
|
|
||||||
engine::{Stack, StateWorkingSet},
|
|
||||||
eval_const::eval_constant,
|
|
||||||
};
|
|
||||||
use reedline::Suggestion;
|
|
||||||
|
|
||||||
use super::completion_options::NuMatcher;
|
|
||||||
|
|
||||||
pub struct CellPathCompletion<'a> {
|
|
||||||
pub full_cell_path: &'a FullCellPath,
|
|
||||||
pub position: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prefix_from_path_member(member: &PathMember, pos: usize) -> (String, Span) {
|
|
||||||
let (prefix_str, start) = match member {
|
|
||||||
PathMember::String { val, span, .. } => (val, span.start),
|
|
||||||
PathMember::Int { val, span, .. } => (&val.to_string(), span.start),
|
|
||||||
};
|
|
||||||
let prefix_str = prefix_str.get(..pos + 1 - start).unwrap_or(prefix_str);
|
|
||||||
// strip wrapping quotes
|
|
||||||
let quotations = ['"', '\'', '`'];
|
|
||||||
let prefix_str = prefix_str.strip_prefix(quotations).unwrap_or(prefix_str);
|
|
||||||
(prefix_str.to_string(), Span::new(start, pos + 1))
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Completer for CellPathCompletion<'_> {
|
|
||||||
fn fetch(
|
|
||||||
&mut self,
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
stack: &Stack,
|
|
||||||
_prefix: impl AsRef<str>,
|
|
||||||
_span: Span,
|
|
||||||
offset: usize,
|
|
||||||
options: &CompletionOptions,
|
|
||||||
) -> Vec<SemanticSuggestion> {
|
|
||||||
let mut prefix_str = String::new();
|
|
||||||
// position at dots, e.g. `$env.config.<TAB>`
|
|
||||||
let mut span = Span::new(self.position + 1, self.position + 1);
|
|
||||||
let mut path_member_num_before_pos = 0;
|
|
||||||
for member in self.full_cell_path.tail.iter() {
|
|
||||||
if member.span().end <= self.position {
|
|
||||||
path_member_num_before_pos += 1;
|
|
||||||
} else if member.span().contains(self.position) {
|
|
||||||
(prefix_str, span) = prefix_from_path_member(member, self.position);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let current_span = reedline::Span {
|
|
||||||
start: span.start - offset,
|
|
||||||
end: span.end - offset,
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut matcher = NuMatcher::new(prefix_str, options);
|
|
||||||
let path_members = self
|
|
||||||
.full_cell_path
|
|
||||||
.tail
|
|
||||||
.get(0..path_member_num_before_pos)
|
|
||||||
.unwrap_or_default();
|
|
||||||
let value = eval_cell_path(
|
|
||||||
working_set,
|
|
||||||
stack,
|
|
||||||
&self.full_cell_path.head,
|
|
||||||
path_members,
|
|
||||||
span,
|
|
||||||
)
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
for suggestion in get_suggestions_by_value(&value, current_span) {
|
|
||||||
matcher.add_semantic_suggestion(suggestion);
|
|
||||||
}
|
|
||||||
matcher.results()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Follow cell path to get the value
|
|
||||||
/// NOTE: This is a relatively lightweight implementation,
|
|
||||||
/// so it may fail to get the exact value when the expression is complicated.
|
|
||||||
/// One failing example would be `[$foo].0`
|
|
||||||
pub(crate) fn eval_cell_path(
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
stack: &Stack,
|
|
||||||
head: &Expression,
|
|
||||||
path_members: &[PathMember],
|
|
||||||
span: Span,
|
|
||||||
) -> Result<Value, ShellError> {
|
|
||||||
// evaluate the head expression to get its value
|
|
||||||
let head_value = if let Expr::Var(var_id) = head.expr {
|
|
||||||
working_set
|
|
||||||
.get_variable(var_id)
|
|
||||||
.const_val
|
|
||||||
.to_owned()
|
|
||||||
.map_or_else(
|
|
||||||
|| eval_variable(working_set.permanent_state, stack, var_id, span),
|
|
||||||
Ok,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
eval_constant(working_set, head)
|
|
||||||
}?;
|
|
||||||
head_value
|
|
||||||
.follow_cell_path(path_members)
|
|
||||||
.map(Cow::into_owned)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_suggestions_by_value(
|
|
||||||
value: &Value,
|
|
||||||
current_span: reedline::Span,
|
|
||||||
) -> Vec<SemanticSuggestion> {
|
|
||||||
let to_suggestion = |s: String, v: Option<&Value>| {
|
|
||||||
// Check if the string needs quoting
|
|
||||||
let value = if s.is_empty()
|
|
||||||
|| s.chars()
|
|
||||||
.any(|c: char| !(c.is_ascii_alphabetic() || ['_', '-'].contains(&c)))
|
|
||||||
{
|
|
||||||
format!("{s:?}")
|
|
||||||
} else {
|
|
||||||
s
|
|
||||||
};
|
|
||||||
|
|
||||||
SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value,
|
|
||||||
span: current_span,
|
|
||||||
description: v.map(|v| v.get_type().to_string()),
|
|
||||||
..Suggestion::default()
|
|
||||||
},
|
|
||||||
kind: Some(SuggestionKind::CellPath),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
match value {
|
|
||||||
Value::Record { val, .. } => val
|
|
||||||
.columns()
|
|
||||||
.map(|s| to_suggestion(s.to_string(), val.get(s)))
|
|
||||||
.collect(),
|
|
||||||
Value::List { vals, .. } => get_columns(vals.as_slice())
|
|
||||||
.into_iter()
|
|
||||||
.map(|s| {
|
|
||||||
let sub_val = vals
|
|
||||||
.first()
|
|
||||||
.and_then(|v| v.as_record().ok())
|
|
||||||
.and_then(|rv| rv.get(&s));
|
|
||||||
to_suggestion(s, sub_val)
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
_ => vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,86 +1,67 @@
|
|||||||
use std::collections::HashMap;
|
use crate::completions::{Completer, CompletionOptions, MatchAlgorithm, SortBy};
|
||||||
|
use nu_parser::FlatShape;
|
||||||
use crate::{
|
|
||||||
SuggestionKind,
|
|
||||||
completions::{Completer, CompletionOptions},
|
|
||||||
};
|
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
|
engine::{EngineState, StateWorkingSet},
|
||||||
Span,
|
Span,
|
||||||
engine::{CommandType, Stack, StateWorkingSet},
|
|
||||||
};
|
};
|
||||||
use reedline::Suggestion;
|
use reedline::Suggestion;
|
||||||
|
use std::sync::Arc;
|
||||||
use super::{SemanticSuggestion, completion_options::NuMatcher};
|
|
||||||
|
|
||||||
pub struct CommandCompletion {
|
pub struct CommandCompletion {
|
||||||
/// Whether to include internal commands
|
engine_state: Arc<EngineState>,
|
||||||
pub internals: bool,
|
flattened: Vec<(Span, FlatShape)>,
|
||||||
/// Whether to include external commands
|
flat_shape: FlatShape,
|
||||||
pub externals: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommandCompletion {
|
impl CommandCompletion {
|
||||||
|
pub fn new(
|
||||||
|
engine_state: Arc<EngineState>,
|
||||||
|
_: &StateWorkingSet,
|
||||||
|
flattened: Vec<(Span, FlatShape)>,
|
||||||
|
flat_shape: FlatShape,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
engine_state,
|
||||||
|
flattened,
|
||||||
|
flat_shape,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn external_command_completion(
|
fn external_command_completion(
|
||||||
&self,
|
&self,
|
||||||
working_set: &StateWorkingSet,
|
prefix: &str,
|
||||||
sugg_span: reedline::Span,
|
match_algorithm: MatchAlgorithm,
|
||||||
matched_internal: impl Fn(&str) -> bool,
|
) -> Vec<String> {
|
||||||
matcher: &mut NuMatcher<String>,
|
let mut executables = vec![];
|
||||||
) -> HashMap<String, SemanticSuggestion> {
|
|
||||||
let mut suggs = HashMap::new();
|
|
||||||
|
|
||||||
let paths = working_set.permanent_state.get_env_var_insensitive("path");
|
let paths = self.engine_state.get_env_var("PATH");
|
||||||
|
|
||||||
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
|
> executables.len() as i64
|
||||||
.config
|
&& !executables.contains(
|
||||||
.completions
|
&item
|
||||||
.external
|
.path()
|
||||||
.max_results
|
.file_name()
|
||||||
<= suggs.len() as i64
|
.map(|x| x.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
)
|
||||||
|
&& matches!(
|
||||||
|
item.path().file_name().map(|x| match_algorithm
|
||||||
|
.matches_str(&x.to_string_lossy(), prefix)),
|
||||||
|
Some(true)
|
||||||
|
)
|
||||||
|
&& is_executable::is_executable(&item.path())
|
||||||
{
|
{
|
||||||
break;
|
if let Ok(name) = item.file_name().into_string() {
|
||||||
}
|
executables.push(name);
|
||||||
let Ok(name) = item.file_name().into_string() else {
|
}
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let value = if matched_internal(&name) {
|
|
||||||
format!("^{name}")
|
|
||||||
} else {
|
|
||||||
name.clone()
|
|
||||||
};
|
|
||||||
if suggs.contains_key(&value) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// TODO: check name matching before a relative heavy IO involved
|
|
||||||
// `is_executable` for performance consideration, should avoid
|
|
||||||
// duplicated `match_aux` call for matched items in the future
|
|
||||||
if matcher.matches(&name) && is_executable::is_executable(item.path()) {
|
|
||||||
// If there's an internal command with the same name, adds ^cmd to the
|
|
||||||
// matcher so that both the internal and external command are included
|
|
||||||
matcher.add(&name, value.clone());
|
|
||||||
suggs.insert(
|
|
||||||
value.clone(),
|
|
||||||
SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value,
|
|
||||||
span: sugg_span,
|
|
||||||
append_whitespace: true,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
kind: Some(SuggestionKind::Command(
|
|
||||||
CommandType::External,
|
|
||||||
None,
|
|
||||||
)),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,7 +69,88 @@ impl CommandCompletion {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suggs
|
executables
|
||||||
|
}
|
||||||
|
|
||||||
|
fn complete_commands(
|
||||||
|
&self,
|
||||||
|
working_set: &StateWorkingSet,
|
||||||
|
span: Span,
|
||||||
|
offset: usize,
|
||||||
|
find_externals: bool,
|
||||||
|
match_algorithm: MatchAlgorithm,
|
||||||
|
) -> Vec<Suggestion> {
|
||||||
|
let partial = working_set.get_span_contents(span);
|
||||||
|
|
||||||
|
let filter_predicate = |command: &[u8]| match_algorithm.matches_u8(command, partial);
|
||||||
|
|
||||||
|
let results = working_set
|
||||||
|
.find_commands_by_predicate(filter_predicate)
|
||||||
|
.into_iter()
|
||||||
|
.map(move |x| Suggestion {
|
||||||
|
value: String::from_utf8_lossy(&x.0).to_string(),
|
||||||
|
description: x.1,
|
||||||
|
extra: None,
|
||||||
|
span: reedline::Span {
|
||||||
|
start: span.start - offset,
|
||||||
|
end: span.end - offset,
|
||||||
|
},
|
||||||
|
append_whitespace: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
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 = String::from_utf8_lossy(partial).to_string();
|
||||||
|
let results = if find_externals {
|
||||||
|
let results_external = self
|
||||||
|
.external_command_completion(&partial, match_algorithm)
|
||||||
|
.into_iter()
|
||||||
|
.map(move |x| Suggestion {
|
||||||
|
value: x,
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
|
span: reedline::Span {
|
||||||
|
start: span.start - offset,
|
||||||
|
end: span.end - offset,
|
||||||
|
},
|
||||||
|
append_whitespace: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
for external in results_external {
|
||||||
|
if results.contains(&external) {
|
||||||
|
results.push(Suggestion {
|
||||||
|
value: format!("^{}", external.value),
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
|
span: external.span,
|
||||||
|
append_whitespace: true,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
results.push(external)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
results
|
||||||
|
} else {
|
||||||
|
results
|
||||||
|
};
|
||||||
|
|
||||||
|
results
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,63 +158,73 @@ impl Completer for CommandCompletion {
|
|||||||
fn fetch(
|
fn fetch(
|
||||||
&mut self,
|
&mut self,
|
||||||
working_set: &StateWorkingSet,
|
working_set: &StateWorkingSet,
|
||||||
_stack: &Stack,
|
_prefix: Vec<u8>,
|
||||||
prefix: impl AsRef<str>,
|
|
||||||
span: Span,
|
span: Span,
|
||||||
offset: usize,
|
offset: usize,
|
||||||
|
pos: usize,
|
||||||
options: &CompletionOptions,
|
options: &CompletionOptions,
|
||||||
) -> Vec<SemanticSuggestion> {
|
) -> Vec<Suggestion> {
|
||||||
let mut matcher = NuMatcher::new(prefix, options);
|
let last = self
|
||||||
|
.flattened
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.skip_while(|x| x.0.end > pos)
|
||||||
|
.take_while(|x| {
|
||||||
|
matches!(
|
||||||
|
x.1,
|
||||||
|
FlatShape::InternalCall
|
||||||
|
| FlatShape::External
|
||||||
|
| FlatShape::ExternalArg
|
||||||
|
| FlatShape::Literal
|
||||||
|
| FlatShape::String
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.last();
|
||||||
|
|
||||||
let sugg_span = reedline::Span::new(span.start - offset, span.end - offset);
|
// The last item here would be the earliest shape that could possible by part of this subcommand
|
||||||
|
let subcommands = if let Some(last) = last {
|
||||||
let mut internal_suggs = HashMap::new();
|
self.complete_commands(
|
||||||
if self.internals {
|
|
||||||
let filtered_commands = working_set.find_commands_by_predicate(
|
|
||||||
|name| {
|
|
||||||
let name = String::from_utf8_lossy(name);
|
|
||||||
matcher.add(&name, name.to_string())
|
|
||||||
},
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
for (decl_id, name, description, typ) in filtered_commands {
|
|
||||||
let name = String::from_utf8_lossy(&name);
|
|
||||||
internal_suggs.insert(
|
|
||||||
name.to_string(),
|
|
||||||
SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value: name.to_string(),
|
|
||||||
description,
|
|
||||||
span: sugg_span,
|
|
||||||
append_whitespace: true,
|
|
||||||
..Suggestion::default()
|
|
||||||
},
|
|
||||||
kind: Some(SuggestionKind::Command(typ, Some(decl_id))),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut external_suggs = if self.externals {
|
|
||||||
self.external_command_completion(
|
|
||||||
working_set,
|
working_set,
|
||||||
sugg_span,
|
Span {
|
||||||
|name| internal_suggs.contains_key(name),
|
start: last.0.start,
|
||||||
&mut matcher,
|
end: pos,
|
||||||
|
},
|
||||||
|
offset,
|
||||||
|
false,
|
||||||
|
options.match_algorithm,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
HashMap::new()
|
vec![]
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut res = Vec::new();
|
if !subcommands.is_empty() {
|
||||||
for cmd_name in matcher.results() {
|
return subcommands;
|
||||||
if let Some(sugg) = internal_suggs
|
|
||||||
.remove(&cmd_name)
|
|
||||||
.or_else(|| external_suggs.remove(&cmd_name))
|
|
||||||
{
|
|
||||||
res.push(sugg);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
res
|
|
||||||
|
let config = working_set.get_config();
|
||||||
|
let commands = if matches!(self.flat_shape, nu_parser::FlatShape::External)
|
||||||
|
|| matches!(self.flat_shape, nu_parser::FlatShape::InternalCall)
|
||||||
|
|| ((span.end - span.start) == 0)
|
||||||
|
{
|
||||||
|
// we're in a gap or at a command
|
||||||
|
self.complete_commands(
|
||||||
|
working_set,
|
||||||
|
span,
|
||||||
|
offset,
|
||||||
|
config.enable_external_completion,
|
||||||
|
options.match_algorithm,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
vec![]
|
||||||
|
};
|
||||||
|
|
||||||
|
subcommands
|
||||||
|
.into_iter()
|
||||||
|
.chain(commands.into_iter())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_sort_by(&self) -> SortBy {
|
||||||
|
SortBy::LevenshteinDistance
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,401 +0,0 @@
|
|||||||
use super::{MatchAlgorithm, completion_options::NuMatcher};
|
|
||||||
use crate::completions::CompletionOptions;
|
|
||||||
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::{
|
|
||||||
Span,
|
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
|
||||||
};
|
|
||||||
use nu_utils::IgnoreCaseExt;
|
|
||||||
use nu_utils::get_ls_colors;
|
|
||||||
use std::path::{Component, MAIN_SEPARATOR as SEP, Path, PathBuf, is_separator};
|
|
||||||
|
|
||||||
#[derive(Clone, Default)]
|
|
||||||
pub struct PathBuiltFromString {
|
|
||||||
cwd: PathBuf,
|
|
||||||
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.
|
|
||||||
///
|
|
||||||
/// `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.
|
|
||||||
///
|
|
||||||
/// `isdir`: whether the current partial path has a trailing slash.
|
|
||||||
/// Parsing a path string into a pathbuf loses that bit of information.
|
|
||||||
///
|
|
||||||
/// `enable_exact_match`: Whether match algorithm is Prefix and all previous components
|
|
||||||
/// of the path matched a directory exactly.
|
|
||||||
fn complete_rec(
|
|
||||||
partial: &[&str],
|
|
||||||
built_paths: &[PathBuiltFromString],
|
|
||||||
options: &CompletionOptions,
|
|
||||||
want_directory: bool,
|
|
||||||
isdir: bool,
|
|
||||||
enable_exact_match: bool,
|
|
||||||
) -> Vec<PathBuiltFromString> {
|
|
||||||
let has_more = !partial.is_empty() && (partial.len() > 1 || isdir);
|
|
||||||
|
|
||||||
if let Some((&base, rest)) = partial.split_first() {
|
|
||||||
if base.chars().all(|c| c == '.') && has_more {
|
|
||||||
let built_paths: Vec<_> = built_paths
|
|
||||||
.iter()
|
|
||||||
.map(|built| {
|
|
||||||
let mut built = built.clone();
|
|
||||||
built.parts.push(base.to_string());
|
|
||||||
built.isdir = true;
|
|
||||||
built
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
return complete_rec(
|
|
||||||
rest,
|
|
||||||
&built_paths,
|
|
||||||
options,
|
|
||||||
want_directory,
|
|
||||||
isdir,
|
|
||||||
enable_exact_match,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let prefix = partial.first().unwrap_or(&"");
|
|
||||||
let mut matcher = NuMatcher::new(prefix, options);
|
|
||||||
|
|
||||||
let mut exact_match = None;
|
|
||||||
// Only relevant for case insensitive matching
|
|
||||||
let mut multiple_exact_matches = false;
|
|
||||||
for built in built_paths {
|
|
||||||
let mut path = built.cwd.clone();
|
|
||||||
for part in &built.parts {
|
|
||||||
path.push(part);
|
|
||||||
}
|
|
||||||
|
|
||||||
let Ok(result) = path.read_dir() else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
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());
|
|
||||||
// Symlinks to directories shouldn't have a trailing slash (#13275)
|
|
||||||
built.isdir = entry_isdir && !entry.path().is_symlink();
|
|
||||||
|
|
||||||
if !want_directory || entry_isdir {
|
|
||||||
if enable_exact_match && !multiple_exact_matches && has_more {
|
|
||||||
let matches = if options.case_sensitive {
|
|
||||||
entry_name.eq(prefix)
|
|
||||||
} else {
|
|
||||||
entry_name.eq_ignore_case(prefix)
|
|
||||||
};
|
|
||||||
if matches {
|
|
||||||
if exact_match.is_none() {
|
|
||||||
exact_match = Some(built.clone());
|
|
||||||
} else {
|
|
||||||
multiple_exact_matches = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
matcher.add(entry_name, built);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't show longer completions if we have a single exact match (#13204, #14794)
|
|
||||||
if !multiple_exact_matches {
|
|
||||||
if let Some(built) = exact_match {
|
|
||||||
return complete_rec(
|
|
||||||
&partial[1..],
|
|
||||||
&[built],
|
|
||||||
options,
|
|
||||||
want_directory,
|
|
||||||
isdir,
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if has_more {
|
|
||||||
let mut completions = vec![];
|
|
||||||
for built in matcher.results() {
|
|
||||||
completions.extend(complete_rec(
|
|
||||||
&partial[1..],
|
|
||||||
&[built],
|
|
||||||
options,
|
|
||||||
want_directory,
|
|
||||||
isdir,
|
|
||||||
false,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
completions
|
|
||||||
} else {
|
|
||||||
matcher.results()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub 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 struct FileSuggestion {
|
|
||||||
pub span: nu_protocol::Span,
|
|
||||||
pub path: String,
|
|
||||||
pub style: Option<Style>,
|
|
||||||
pub is_dir: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// # Parameters
|
|
||||||
/// * `cwds` - A list of directories in which to search. The only reason this isn't a single string
|
|
||||||
/// is because dotnu_completions searches in multiple directories at once
|
|
||||||
pub fn complete_item(
|
|
||||||
want_directory: bool,
|
|
||||||
span: nu_protocol::Span,
|
|
||||||
partial: &str,
|
|
||||||
cwds: &[impl AsRef<str>],
|
|
||||||
options: &CompletionOptions,
|
|
||||||
engine_state: &EngineState,
|
|
||||||
stack: &Stack,
|
|
||||||
) -> Vec<FileSuggestion> {
|
|
||||||
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_pathbufs: Vec<_> = cwds
|
|
||||||
.iter()
|
|
||||||
.map(|cwd| Path::new(cwd.as_ref()).to_path_buf())
|
|
||||||
.collect();
|
|
||||||
let ls_colors = (engine_state.config.completions.use_ls_colors
|
|
||||||
&& engine_state.config.use_ansi_coloring.get(engine_state))
|
|
||||||
.then(|| {
|
|
||||||
let ls_colors_env_str = stack
|
|
||||||
.get_env_var(engine_state, "LS_COLORS")
|
|
||||||
.and_then(|v| env_to_string("LS_COLORS", v, engine_state, stack).ok());
|
|
||||||
get_ls_colors(ls_colors_env_str)
|
|
||||||
});
|
|
||||||
|
|
||||||
let mut cwds = cwd_pathbufs.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
|
|
||||||
cwds = vec![[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
|
|
||||||
cwds = vec![PathBuf::from(c.as_os_str())];
|
|
||||||
prefix_len = 1;
|
|
||||||
original_cwd = OriginalCwd::Prefix(String::new());
|
|
||||||
}
|
|
||||||
Some(Component::Normal(home)) if home.to_string_lossy() == "~" => {
|
|
||||||
cwds = home_dir()
|
|
||||||
.map(|dir| vec![dir.into()])
|
|
||||||
.unwrap_or(cwd_pathbufs);
|
|
||||||
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(),
|
|
||||||
&cwds
|
|
||||||
.into_iter()
|
|
||||||
.map(|cwd| PathBuiltFromString {
|
|
||||||
cwd,
|
|
||||||
parts: Vec::new(),
|
|
||||||
isdir: false,
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
options,
|
|
||||||
want_directory,
|
|
||||||
isdir,
|
|
||||||
options.match_algorithm == MatchAlgorithm::Prefix,
|
|
||||||
)
|
|
||||||
.into_iter()
|
|
||||||
.map(|mut p| {
|
|
||||||
if should_collapse_dots {
|
|
||||||
p = collapse_ndots(p);
|
|
||||||
}
|
|
||||||
let is_dir = p.isdir;
|
|
||||||
let path = original_cwd.apply(p, path_separator);
|
|
||||||
let real_path = expand_to_real_path(&path);
|
|
||||||
let metadata = std::fs::symlink_metadata(&real_path).ok();
|
|
||||||
let style = ls_colors.as_ref().map(|lsc| {
|
|
||||||
lsc.style_for_path_with_metadata(&real_path, metadata.as_ref())
|
|
||||||
.map(lscolors::Style::to_nu_ansi_term_style)
|
|
||||||
.unwrap_or_default()
|
|
||||||
});
|
|
||||||
FileSuggestion {
|
|
||||||
span,
|
|
||||||
path: escape_path(path),
|
|
||||||
style,
|
|
||||||
is_dir,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fix files or folders with quotes or hashes
|
|
||||||
pub fn escape_path(path: String) -> String {
|
|
||||||
// make glob pattern have the highest priority.
|
|
||||||
if nu_glob::is_glob(path.as_str()) || path.contains('`') {
|
|
||||||
// expand home `~` for https://github.com/nushell/nushell/issues/13905
|
|
||||||
let pathbuf = nu_path::expand_tilde(path);
|
|
||||||
let path = pathbuf.to_string_lossy();
|
|
||||||
if path.contains('\'') {
|
|
||||||
// decide to use double quotes
|
|
||||||
// Path as Debug will do the escaping for `"`, `\`
|
|
||||||
format!("{path:?}")
|
|
||||||
} else {
|
|
||||||
format!("'{path}'")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let contaminated =
|
|
||||||
path.contains(['\'', '"', ' ', '#', '(', ')', '{', '}', '[', ']', '|', ';']);
|
|
||||||
let maybe_flag = path.starts_with('-');
|
|
||||||
let maybe_variable = path.starts_with('$');
|
|
||||||
let maybe_number = path.parse::<f64>().is_ok();
|
|
||||||
if 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: &str,
|
|
||||||
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 = 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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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,
|
|
||||||
cwd: path.cwd,
|
|
||||||
};
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,17 @@
|
|||||||
use nu_parser::trim_quotes_str;
|
use std::fmt::Display;
|
||||||
use nu_protocol::{CompletionAlgorithm, CompletionSort};
|
|
||||||
use nu_utils::IgnoreCaseExt;
|
|
||||||
use nucleo_matcher::{
|
|
||||||
Config, Matcher, Utf32Str,
|
|
||||||
pattern::{Atom, AtomKind, CaseMatching, Normalization},
|
|
||||||
};
|
|
||||||
use std::{borrow::Cow, fmt::Display};
|
|
||||||
|
|
||||||
use super::SemanticSuggestion;
|
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
|
||||||
///
|
///
|
||||||
@@ -18,12 +19,6 @@ pub enum MatchAlgorithm {
|
|||||||
/// "git switch" is matched by "git sw"
|
/// "git switch" is matched by "git sw"
|
||||||
Prefix,
|
Prefix,
|
||||||
|
|
||||||
/// Only show suggestions which have a substring matching with the given input
|
|
||||||
///
|
|
||||||
/// Example:
|
|
||||||
/// "git checkout" is matched by "checkout"
|
|
||||||
Substring,
|
|
||||||
|
|
||||||
/// Only show suggestions which contain the input chars at any place
|
/// Only show suggestions which contain the input chars at any place
|
||||||
///
|
///
|
||||||
/// Example:
|
/// Example:
|
||||||
@@ -31,208 +26,31 @@ pub enum MatchAlgorithm {
|
|||||||
Fuzzy,
|
Fuzzy,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct NuMatcher<'a, T> {
|
impl MatchAlgorithm {
|
||||||
options: &'a CompletionOptions,
|
/// Returns whether the `needle` search text matches the given `haystack`.
|
||||||
needle: String,
|
pub fn matches_str(&self, haystack: &str, needle: &str) -> bool {
|
||||||
state: State<T>,
|
|
||||||
}
|
|
||||||
|
|
||||||
enum State<T> {
|
|
||||||
Prefix {
|
|
||||||
/// Holds (haystack, item)
|
|
||||||
items: Vec<(String, T)>,
|
|
||||||
},
|
|
||||||
Substring {
|
|
||||||
/// Holds (haystack, item)
|
|
||||||
items: Vec<(String, T)>,
|
|
||||||
},
|
|
||||||
Fuzzy {
|
|
||||||
matcher: Matcher,
|
|
||||||
atom: Atom,
|
|
||||||
/// Holds (haystack, item, score)
|
|
||||||
items: Vec<(String, T, u16)>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Filters and sorts suggestions
|
|
||||||
impl<T> NuMatcher<'_, T> {
|
|
||||||
/// # Arguments
|
|
||||||
///
|
|
||||||
/// * `needle` - The text to search for
|
|
||||||
pub fn new(needle: impl AsRef<str>, options: &CompletionOptions) -> NuMatcher<T> {
|
|
||||||
let needle = trim_quotes_str(needle.as_ref());
|
|
||||||
match options.match_algorithm {
|
|
||||||
MatchAlgorithm::Prefix => {
|
|
||||||
let lowercase_needle = if options.case_sensitive {
|
|
||||||
needle.to_owned()
|
|
||||||
} else {
|
|
||||||
needle.to_folded_case()
|
|
||||||
};
|
|
||||||
NuMatcher {
|
|
||||||
options,
|
|
||||||
needle: lowercase_needle,
|
|
||||||
state: State::Prefix { items: Vec::new() },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
MatchAlgorithm::Substring => {
|
|
||||||
let lowercase_needle = if options.case_sensitive {
|
|
||||||
needle.to_owned()
|
|
||||||
} else {
|
|
||||||
needle.to_folded_case()
|
|
||||||
};
|
|
||||||
NuMatcher {
|
|
||||||
options,
|
|
||||||
needle: lowercase_needle,
|
|
||||||
state: State::Substring { items: Vec::new() },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
MatchAlgorithm::Fuzzy => {
|
|
||||||
let atom = Atom::new(
|
|
||||||
needle,
|
|
||||||
if options.case_sensitive {
|
|
||||||
CaseMatching::Respect
|
|
||||||
} else {
|
|
||||||
CaseMatching::Ignore
|
|
||||||
},
|
|
||||||
Normalization::Smart,
|
|
||||||
AtomKind::Fuzzy,
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
NuMatcher {
|
|
||||||
options,
|
|
||||||
needle: needle.to_owned(),
|
|
||||||
state: State::Fuzzy {
|
|
||||||
matcher: Matcher::new({
|
|
||||||
let mut cfg = Config::DEFAULT;
|
|
||||||
cfg.prefer_prefix = true;
|
|
||||||
cfg
|
|
||||||
}),
|
|
||||||
atom,
|
|
||||||
items: Vec::new(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns whether or not the haystack matches the needle. If it does, `item` is added
|
|
||||||
/// to the list of matches (if given).
|
|
||||||
///
|
|
||||||
/// Helper to avoid code duplication between [NuMatcher::add] and [NuMatcher::matches].
|
|
||||||
fn matches_aux(&mut self, haystack: &str, item: Option<T>) -> bool {
|
|
||||||
let haystack = trim_quotes_str(haystack);
|
let haystack = trim_quotes_str(haystack);
|
||||||
match &mut self.state {
|
let needle = trim_quotes_str(needle);
|
||||||
State::Prefix { items } => {
|
match *self {
|
||||||
let haystack_folded = if self.options.case_sensitive {
|
MatchAlgorithm::Prefix => haystack.starts_with(needle),
|
||||||
Cow::Borrowed(haystack)
|
MatchAlgorithm::Fuzzy => {
|
||||||
} else {
|
let matcher = SkimMatcherV2::default();
|
||||||
Cow::Owned(haystack.to_folded_case())
|
matcher.fuzzy_match(haystack, needle).is_some()
|
||||||
};
|
|
||||||
let matches = haystack_folded.starts_with(self.needle.as_str());
|
|
||||||
if matches {
|
|
||||||
if let Some(item) = item {
|
|
||||||
items.push((haystack.to_string(), item));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
matches
|
|
||||||
}
|
|
||||||
State::Substring { items } => {
|
|
||||||
let haystack_folded = if self.options.case_sensitive {
|
|
||||||
Cow::Borrowed(haystack)
|
|
||||||
} else {
|
|
||||||
Cow::Owned(haystack.to_folded_case())
|
|
||||||
};
|
|
||||||
let matches = haystack_folded.contains(self.needle.as_str());
|
|
||||||
if matches {
|
|
||||||
if let Some(item) = item {
|
|
||||||
items.push((haystack.to_string(), item));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
matches
|
|
||||||
}
|
|
||||||
State::Fuzzy {
|
|
||||||
matcher,
|
|
||||||
atom,
|
|
||||||
items,
|
|
||||||
} => {
|
|
||||||
let mut haystack_buf = Vec::new();
|
|
||||||
let haystack_utf32 = Utf32Str::new(trim_quotes_str(haystack), &mut haystack_buf);
|
|
||||||
let mut indices = Vec::new();
|
|
||||||
let Some(score) = atom.indices(haystack_utf32, matcher, &mut indices) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
if let Some(item) = item {
|
|
||||||
items.push((haystack.to_string(), item, score));
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add the given item if the given haystack matches the needle.
|
/// Returns whether the `needle` search text matches the given `haystack`.
|
||||||
///
|
pub fn matches_u8(&self, haystack: &[u8], needle: &[u8]) -> bool {
|
||||||
/// Returns whether the item was added.
|
match *self {
|
||||||
pub fn add(&mut self, haystack: impl AsRef<str>, item: T) -> bool {
|
MatchAlgorithm::Prefix => haystack.starts_with(needle),
|
||||||
self.matches_aux(haystack.as_ref(), Some(item))
|
MatchAlgorithm::Fuzzy => {
|
||||||
}
|
let haystack_str = String::from_utf8_lossy(haystack);
|
||||||
|
let needle_str = String::from_utf8_lossy(needle);
|
||||||
|
|
||||||
/// Returns whether the haystack matches the needle.
|
let matcher = SkimMatcherV2::default();
|
||||||
pub fn matches(&mut self, haystack: &str) -> bool {
|
matcher.fuzzy_match(&haystack_str, &needle_str).is_some()
|
||||||
self.matches_aux(haystack, None)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get all the items that matched (sorted)
|
|
||||||
pub fn results(self) -> Vec<T> {
|
|
||||||
match self.state {
|
|
||||||
State::Prefix { mut items, .. } | State::Substring { mut items, .. } => {
|
|
||||||
items.sort_by(|(haystack1, _), (haystack2, _)| {
|
|
||||||
let cmp_sensitive = haystack1.cmp(haystack2);
|
|
||||||
if self.options.case_sensitive {
|
|
||||||
cmp_sensitive
|
|
||||||
} else {
|
|
||||||
haystack1
|
|
||||||
.to_folded_case()
|
|
||||||
.cmp(&haystack2.to_folded_case())
|
|
||||||
.then(cmp_sensitive)
|
|
||||||
}
|
|
||||||
});
|
|
||||||
items.into_iter().map(|(_, item)| item).collect::<Vec<_>>()
|
|
||||||
}
|
}
|
||||||
State::Fuzzy { mut items, .. } => {
|
|
||||||
match self.options.sort {
|
|
||||||
CompletionSort::Alphabetical => {
|
|
||||||
items.sort_by(|(haystack1, _, _), (haystack2, _, _)| {
|
|
||||||
haystack1.cmp(haystack2)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
CompletionSort::Smart => {
|
|
||||||
items.sort_by(|(haystack1, _, score1), (haystack2, _, score2)| {
|
|
||||||
score2.cmp(score1).then(haystack1.cmp(haystack2))
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
items
|
|
||||||
.into_iter()
|
|
||||||
.map(|(_, item, _)| item)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NuMatcher<'_, SemanticSuggestion> {
|
|
||||||
pub fn add_semantic_suggestion(&mut self, sugg: SemanticSuggestion) -> bool {
|
|
||||||
let value = sugg.suggestion.value.to_string();
|
|
||||||
self.add(value, sugg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<CompletionAlgorithm> for MatchAlgorithm {
|
|
||||||
fn from(value: CompletionAlgorithm) -> Self {
|
|
||||||
match value {
|
|
||||||
CompletionAlgorithm::Prefix => MatchAlgorithm::Prefix,
|
|
||||||
CompletionAlgorithm::Substring => MatchAlgorithm::Substring,
|
|
||||||
CompletionAlgorithm::Fuzzy => MatchAlgorithm::Fuzzy,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -243,7 +61,6 @@ impl TryFrom<String> for MatchAlgorithm {
|
|||||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||||
match value.as_str() {
|
match value.as_str() {
|
||||||
"prefix" => Ok(Self::Prefix),
|
"prefix" => Ok(Self::Prefix),
|
||||||
"substring" => Ok(Self::Substring),
|
|
||||||
"fuzzy" => Ok(Self::Fuzzy),
|
"fuzzy" => Ok(Self::Fuzzy),
|
||||||
_ => Err(InvalidMatchAlgorithm::Unknown),
|
_ => Err(InvalidMatchAlgorithm::Unknown),
|
||||||
}
|
}
|
||||||
@@ -268,86 +85,53 @@ impl std::error::Error for InvalidMatchAlgorithm {}
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct CompletionOptions {
|
pub struct CompletionOptions {
|
||||||
pub case_sensitive: bool,
|
pub case_sensitive: 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 {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
case_sensitive: true,
|
case_sensitive: true,
|
||||||
|
positional: true,
|
||||||
|
sort_by: SortBy::Ascending,
|
||||||
match_algorithm: MatchAlgorithm::Prefix,
|
match_algorithm: MatchAlgorithm::Prefix,
|
||||||
sort: Default::default(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use rstest::rstest;
|
use super::MatchAlgorithm;
|
||||||
|
|
||||||
use super::{CompletionOptions, MatchAlgorithm, NuMatcher};
|
#[test]
|
||||||
|
fn match_algorithm_prefix() {
|
||||||
|
let algorithm = MatchAlgorithm::Prefix;
|
||||||
|
|
||||||
#[rstest]
|
assert!(algorithm.matches_str("example text", ""));
|
||||||
#[case(MatchAlgorithm::Prefix, "example text", "", true)]
|
assert!(algorithm.matches_str("example text", "examp"));
|
||||||
#[case(MatchAlgorithm::Prefix, "example text", "examp", true)]
|
assert!(!algorithm.matches_str("example text", "text"));
|
||||||
#[case(MatchAlgorithm::Prefix, "example text", "text", false)]
|
|
||||||
#[case(MatchAlgorithm::Substring, "example text", "", true)]
|
assert!(algorithm.matches_u8(&[1, 2, 3], &[]));
|
||||||
#[case(MatchAlgorithm::Substring, "example text", "text", true)]
|
assert!(algorithm.matches_u8(&[1, 2, 3], &[1, 2]));
|
||||||
#[case(MatchAlgorithm::Substring, "example text", "mplxt", false)]
|
assert!(!algorithm.matches_u8(&[1, 2, 3], &[2, 3]));
|
||||||
#[case(MatchAlgorithm::Fuzzy, "example text", "", true)]
|
|
||||||
#[case(MatchAlgorithm::Fuzzy, "example text", "examp", true)]
|
|
||||||
#[case(MatchAlgorithm::Fuzzy, "example text", "ext", true)]
|
|
||||||
#[case(MatchAlgorithm::Fuzzy, "example text", "mplxt", true)]
|
|
||||||
#[case(MatchAlgorithm::Fuzzy, "example text", "mpp", false)]
|
|
||||||
fn match_algorithm_simple(
|
|
||||||
#[case] match_algorithm: MatchAlgorithm,
|
|
||||||
#[case] haystack: &str,
|
|
||||||
#[case] needle: &str,
|
|
||||||
#[case] should_match: bool,
|
|
||||||
) {
|
|
||||||
let options = CompletionOptions {
|
|
||||||
match_algorithm,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let mut matcher = NuMatcher::new(needle, &options);
|
|
||||||
matcher.add(haystack, haystack);
|
|
||||||
if should_match {
|
|
||||||
assert_eq!(vec![haystack], matcher.results());
|
|
||||||
} else {
|
|
||||||
assert_ne!(vec![haystack], matcher.results());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn match_algorithm_fuzzy_sort_score() {
|
fn match_algorithm_fuzzy() {
|
||||||
let options = CompletionOptions {
|
let algorithm = MatchAlgorithm::Fuzzy;
|
||||||
match_algorithm: MatchAlgorithm::Fuzzy,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let mut matcher = NuMatcher::new("fob", &options);
|
|
||||||
for item in ["foo/bar", "fob", "foo bar"] {
|
|
||||||
matcher.add(item, item);
|
|
||||||
}
|
|
||||||
// Sort by score, then in alphabetical order
|
|
||||||
assert_eq!(vec!["fob", "foo bar", "foo/bar"], matcher.results());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
assert!(algorithm.matches_str("example text", ""));
|
||||||
fn match_algorithm_fuzzy_sort_strip() {
|
assert!(algorithm.matches_str("example text", "examp"));
|
||||||
let options = CompletionOptions {
|
assert!(algorithm.matches_str("example text", "ext"));
|
||||||
match_algorithm: MatchAlgorithm::Fuzzy,
|
assert!(algorithm.matches_str("example text", "mplxt"));
|
||||||
..Default::default()
|
assert!(!algorithm.matches_str("example text", "mpp"));
|
||||||
};
|
|
||||||
let mut matcher = NuMatcher::new("'love spaces' ", &options);
|
assert!(algorithm.matches_u8(&[1, 2, 3], &[]));
|
||||||
for item in [
|
assert!(algorithm.matches_u8(&[1, 2, 3], &[1, 2]));
|
||||||
"'i love spaces'",
|
assert!(algorithm.matches_u8(&[1, 2, 3], &[2, 3]));
|
||||||
"'i love spaces' so much",
|
assert!(algorithm.matches_u8(&[1, 2, 3], &[1, 3]));
|
||||||
"'lovespaces' ",
|
assert!(!algorithm.matches_u8(&[1, 2, 3], &[2, 2]));
|
||||||
] {
|
|
||||||
matcher.add(item, item);
|
|
||||||
}
|
|
||||||
// Make sure the spaces are respected
|
|
||||||
assert_eq!(vec!["'i love spaces' so much"], matcher.results());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,168 +1,233 @@
|
|||||||
use crate::completions::{
|
use crate::completions::{Completer, CompletionOptions, MatchAlgorithm, SortBy};
|
||||||
Completer, CompletionOptions, MatchAlgorithm, SemanticSuggestion,
|
|
||||||
completer::map_value_completions,
|
|
||||||
};
|
|
||||||
use nu_engine::eval_call;
|
use nu_engine::eval_call;
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
DeclId, PipelineData, Span, Type, Value,
|
|
||||||
ast::{Argument, Call, Expr, Expression},
|
ast::{Argument, Call, Expr, Expression},
|
||||||
debugger::WithoutDebug,
|
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
engine::{EngineState, Stack, StateWorkingSet},
|
||||||
|
PipelineData, Span, Type, Value,
|
||||||
};
|
};
|
||||||
use std::collections::HashMap;
|
use reedline::Suggestion;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use super::completion_options::NuMatcher;
|
pub struct CustomCompletion {
|
||||||
|
engine_state: Arc<EngineState>,
|
||||||
pub struct CustomCompletion<T: Completer> {
|
stack: Stack,
|
||||||
decl_id: DeclId,
|
decl_id: usize,
|
||||||
line: String,
|
line: String,
|
||||||
line_pos: usize,
|
sort_by: SortBy,
|
||||||
fallback: T,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Completer> CustomCompletion<T> {
|
impl CustomCompletion {
|
||||||
pub fn new(decl_id: DeclId, line: String, line_pos: usize, fallback: T) -> Self {
|
pub fn new(engine_state: Arc<EngineState>, stack: Stack, decl_id: usize, line: String) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
engine_state,
|
||||||
|
stack,
|
||||||
decl_id,
|
decl_id,
|
||||||
line,
|
line,
|
||||||
line_pos,
|
sort_by: SortBy::None,
|
||||||
fallback,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Completer> Completer for CustomCompletion<T> {
|
fn map_completions<'a>(
|
||||||
fn fetch(
|
&self,
|
||||||
&mut self,
|
list: impl Iterator<Item = &'a Value>,
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
stack: &Stack,
|
|
||||||
prefix: impl AsRef<str>,
|
|
||||||
span: Span,
|
span: Span,
|
||||||
offset: usize,
|
offset: usize,
|
||||||
orig_options: &CompletionOptions,
|
) -> Vec<Suggestion> {
|
||||||
) -> Vec<SemanticSuggestion> {
|
list.filter_map(move |x| {
|
||||||
// Call custom declaration
|
// Match for string values
|
||||||
let mut stack_mut = stack.clone();
|
if let Ok(s) = x.as_string() {
|
||||||
let mut eval = |engine_state: &EngineState| {
|
return Some(Suggestion {
|
||||||
eval_call::<WithoutDebug>(
|
value: s,
|
||||||
engine_state,
|
description: None,
|
||||||
&mut stack_mut,
|
extra: None,
|
||||||
&Call {
|
span: reedline::Span {
|
||||||
decl_id: self.decl_id,
|
start: span.start - offset,
|
||||||
head: span,
|
end: span.end - offset,
|
||||||
arguments: vec![
|
},
|
||||||
Argument::Positional(Expression::new_unknown(
|
append_whitespace: false,
|
||||||
Expr::String(self.line.clone()),
|
});
|
||||||
Span::unknown(),
|
}
|
||||||
Type::String,
|
|
||||||
)),
|
|
||||||
Argument::Positional(Expression::new_unknown(
|
|
||||||
Expr::Int(self.line_pos as i64),
|
|
||||||
Span::unknown(),
|
|
||||||
Type::Int,
|
|
||||||
)),
|
|
||||||
],
|
|
||||||
parser_info: HashMap::new(),
|
|
||||||
},
|
|
||||||
PipelineData::empty(),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
let result = if self.decl_id.get() < working_set.permanent_state.num_decls() {
|
|
||||||
eval(working_set.permanent_state)
|
|
||||||
} else {
|
|
||||||
let mut engine_state = working_set.permanent_state.clone();
|
|
||||||
let _ = engine_state.merge_delta(working_set.delta.clone());
|
|
||||||
eval(&engine_state)
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut completion_options = orig_options.clone();
|
// Match for record values
|
||||||
let mut should_sort = true;
|
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,
|
||||||
|
};
|
||||||
|
|
||||||
// Parse result
|
// Iterate the cols looking for `value` and `description`
|
||||||
let suggestions = match result.and_then(|data| data.into_value(span)) {
|
cols.iter().zip(vals).for_each(|it| {
|
||||||
Ok(value) => match &value {
|
// Match `value` column
|
||||||
Value::Record { val, .. } => {
|
if it.0 == "value" {
|
||||||
let completions = val
|
// Convert the value to string
|
||||||
.get("completions")
|
if let Ok(val_str) = it.1.as_string() {
|
||||||
.and_then(|val| {
|
// Update the suggestion value
|
||||||
val.as_list()
|
suggestion.value = val_str;
|
||||||
.ok()
|
|
||||||
.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 {
|
|
||||||
if let Some(sort) = options.get("sort").and_then(|val| val.as_bool().ok()) {
|
|
||||||
should_sort = sort;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(case_sensitive) = options
|
|
||||||
.get("case_sensitive")
|
|
||||||
.and_then(|val| val.as_bool().ok())
|
|
||||||
{
|
|
||||||
completion_options.case_sensitive = case_sensitive;
|
|
||||||
}
|
|
||||||
let positional =
|
|
||||||
options.get("positional").and_then(|val| val.as_bool().ok());
|
|
||||||
if positional.is_some() {
|
|
||||||
log::warn!(
|
|
||||||
"Use of the positional option is deprecated. Use the substring match algorithm instead."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if let Some(algorithm) = options
|
|
||||||
.get("completion_algorithm")
|
|
||||||
.and_then(|option| option.coerce_string().ok())
|
|
||||||
.and_then(|option| option.try_into().ok())
|
|
||||||
{
|
|
||||||
completion_options.match_algorithm = algorithm;
|
|
||||||
if let Some(false) = positional {
|
|
||||||
if completion_options.match_algorithm == MatchAlgorithm::Prefix {
|
|
||||||
completion_options.match_algorithm = MatchAlgorithm::Substring
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
completions
|
// Match `description` column
|
||||||
}
|
if it.0 == "description" {
|
||||||
Value::List { vals, .. } => map_value_completions(vals.iter(), span, offset),
|
// Convert the value to string
|
||||||
Value::Nothing { .. } => {
|
if let Ok(desc_str) = it.1.as_string() {
|
||||||
return self.fallback.fetch(
|
// Update the suggestion value
|
||||||
working_set,
|
suggestion.description = Some(desc_str);
|
||||||
stack,
|
}
|
||||||
prefix,
|
}
|
||||||
span,
|
});
|
||||||
offset,
|
|
||||||
orig_options,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
log::error!(
|
|
||||||
"Custom completer returned invalid value of type {}",
|
|
||||||
value.get_type().to_string()
|
|
||||||
);
|
|
||||||
return vec![];
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Error getting custom completions: {e}");
|
|
||||||
return vec![];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut matcher = NuMatcher::new(prefix, &completion_options);
|
return Some(suggestion);
|
||||||
|
|
||||||
if should_sort {
|
|
||||||
for sugg in suggestions {
|
|
||||||
matcher.add_semantic_suggestion(sugg);
|
|
||||||
}
|
}
|
||||||
matcher.results()
|
|
||||||
} else {
|
None
|
||||||
suggestions
|
})
|
||||||
.into_iter()
|
.collect()
|
||||||
.filter(|sugg| matcher.matches(&sugg.suggestion.value))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Completer for CustomCompletion {
|
||||||
|
fn fetch(
|
||||||
|
&mut self,
|
||||||
|
_: &StateWorkingSet,
|
||||||
|
prefix: Vec<u8>,
|
||||||
|
span: Span,
|
||||||
|
offset: usize,
|
||||||
|
pos: usize,
|
||||||
|
completion_options: &CompletionOptions,
|
||||||
|
) -> Vec<Suggestion> {
|
||||||
|
// Line position
|
||||||
|
let line_pos = pos - offset;
|
||||||
|
|
||||||
|
// Call custom declaration
|
||||||
|
let result = eval_call(
|
||||||
|
&self.engine_state,
|
||||||
|
&mut self.stack,
|
||||||
|
&Call {
|
||||||
|
decl_id: self.decl_id,
|
||||||
|
head: span,
|
||||||
|
arguments: vec![
|
||||||
|
Argument::Positional(Expression {
|
||||||
|
span: Span { start: 0, end: 0 },
|
||||||
|
ty: Type::String,
|
||||||
|
expr: Expr::String(self.line.clone()),
|
||||||
|
custom_completion: None,
|
||||||
|
}),
|
||||||
|
Argument::Positional(Expression {
|
||||||
|
span: Span { start: 0, end: 0 },
|
||||||
|
ty: Type::Int,
|
||||||
|
expr: Expr::Int(line_pos as i64),
|
||||||
|
custom_completion: None,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
redirect_stdout: true,
|
||||||
|
redirect_stderr: true,
|
||||||
|
},
|
||||||
|
PipelineData::new(span),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut custom_completion_options = None;
|
||||||
|
|
||||||
|
// Parse result
|
||||||
|
let suggestions = match result {
|
||||||
|
Ok(pd) => {
|
||||||
|
let value = pd.into_value(span);
|
||||||
|
match &value {
|
||||||
|
Value::Record { .. } => {
|
||||||
|
let completions = value
|
||||||
|
.get_data_by_key("completions")
|
||||||
|
.and_then(|val| {
|
||||||
|
val.as_list()
|
||||||
|
.ok()
|
||||||
|
.map(|it| self.map_completions(it.iter(), span, offset))
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
let options = value.get_data_by_key("options");
|
||||||
|
|
||||||
|
if let Some(Value::Record { .. }) = &options {
|
||||||
|
let options = options.unwrap_or_default();
|
||||||
|
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, .. } => self.map_completions(vals.iter(), span, offset),
|
||||||
|
_ => vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => vec![],
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(custom_completion_options) = custom_completion_options {
|
||||||
|
filter(&prefix, suggestions, &custom_completion_options)
|
||||||
|
} else {
|
||||||
|
filter(&prefix, suggestions, completion_options)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_sort_by(&self) -> SortBy {
|
||||||
|
self.sort_by
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn filter(prefix: &[u8], items: Vec<Suggestion>, options: &CompletionOptions) -> Vec<Suggestion> {
|
||||||
|
items
|
||||||
|
.into_iter()
|
||||||
|
.filter(|it| match options.match_algorithm {
|
||||||
|
MatchAlgorithm::Prefix => match (options.case_sensitive, options.positional) {
|
||||||
|
(true, true) => it.value.as_bytes().starts_with(prefix),
|
||||||
|
(true, false) => it.value.contains(std::str::from_utf8(prefix).unwrap_or("")),
|
||||||
|
(false, positional) => {
|
||||||
|
let value = it.value.to_lowercase();
|
||||||
|
let prefix = std::str::from_utf8(prefix).unwrap_or("").to_lowercase();
|
||||||
|
if positional {
|
||||||
|
value.starts_with(&prefix)
|
||||||
|
} else {
|
||||||
|
value.contains(&prefix)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
MatchAlgorithm::Fuzzy => options
|
||||||
|
.match_algorithm
|
||||||
|
.matches_u8(it.value.as_bytes(), prefix),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,62 +1,85 @@
|
|||||||
use crate::completions::{
|
use crate::completions::{matches, Completer, CompletionOptions};
|
||||||
Completer, CompletionOptions,
|
|
||||||
completion_common::{AdjustView, adjust_if_intermediate, complete_item},
|
|
||||||
};
|
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
Span,
|
engine::{EngineState, StateWorkingSet},
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
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, SuggestionKind, completion_common::FileSuggestion};
|
use super::{partial_from, prepend_base_dir};
|
||||||
|
|
||||||
pub struct DirectoryCompletion;
|
const SEP: char = std::path::MAIN_SEPARATOR;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct DirectoryCompletion {
|
||||||
|
engine_state: Arc<EngineState>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DirectoryCompletion {
|
||||||
|
pub fn new(engine_state: Arc<EngineState>) -> Self {
|
||||||
|
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: impl AsRef<str>,
|
|
||||||
span: Span,
|
span: Span,
|
||||||
offset: usize,
|
offset: usize,
|
||||||
|
_: usize,
|
||||||
options: &CompletionOptions,
|
options: &CompletionOptions,
|
||||||
) -> Vec<SemanticSuggestion> {
|
) -> Vec<Suggestion> {
|
||||||
let AdjustView { prefix, span, .. } =
|
let cwd = if let Some(d) = self.engine_state.get_env_var("PWD") {
|
||||||
adjust_if_intermediate(prefix.as_ref(), working_set, span);
|
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,
|
value: x.1,
|
||||||
&working_set.permanent_state.current_work_dir(),
|
description: None,
|
||||||
options,
|
extra: None,
|
||||||
working_set.permanent_state,
|
|
||||||
stack,
|
|
||||||
)
|
|
||||||
.into_iter()
|
|
||||||
.map(move |x| SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value: x.path,
|
|
||||||
style: x.style,
|
|
||||||
span: reedline::Span {
|
span: reedline::Span {
|
||||||
start: x.span.start - offset,
|
start: x.0.start - offset,
|
||||||
end: x.span.end - offset,
|
end: x.0.end - offset,
|
||||||
},
|
},
|
||||||
..Suggestion::default()
|
append_whitespace: false,
|
||||||
},
|
})
|
||||||
kind: Some(SuggestionKind::Directory),
|
.collect();
|
||||||
})
|
|
||||||
.collect();
|
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() {
|
||||||
@@ -81,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<FileSuggestion> {
|
|
||||||
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()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,209 +1,124 @@
|
|||||||
use crate::completions::{
|
use crate::completions::{
|
||||||
Completer, CompletionOptions, SemanticSuggestion, SuggestionKind,
|
file_path_completion, partial_from, Completer, CompletionOptions, SortBy,
|
||||||
completion_common::{FileSuggestion, surround_remove},
|
|
||||||
completion_options::NuMatcher,
|
|
||||||
file_path_completion,
|
|
||||||
};
|
};
|
||||||
use nu_path::expand_tilde;
|
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
|
engine::{EngineState, StateWorkingSet},
|
||||||
Span,
|
Span,
|
||||||
engine::{Stack, StateWorkingSet, VirtualPath},
|
|
||||||
};
|
};
|
||||||
use reedline::Suggestion;
|
use reedline::Suggestion;
|
||||||
use std::{
|
use std::sync::Arc;
|
||||||
collections::HashSet,
|
const SEP: char = std::path::MAIN_SEPARATOR;
|
||||||
path::{MAIN_SEPARATOR_STR, PathBuf, is_separator},
|
|
||||||
};
|
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct DotNuCompletion {
|
pub struct DotNuCompletion {
|
||||||
/// e.g. use std/a<tab>
|
engine_state: Arc<EngineState>,
|
||||||
pub std_virtual_path: bool,
|
}
|
||||||
|
|
||||||
|
impl DotNuCompletion {
|
||||||
|
pub fn new(engine_state: Arc<EngineState>) -> Self {
|
||||||
|
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: impl AsRef<str>,
|
|
||||||
span: Span,
|
span: Span,
|
||||||
offset: usize,
|
offset: usize,
|
||||||
|
_: usize,
|
||||||
options: &CompletionOptions,
|
options: &CompletionOptions,
|
||||||
) -> Vec<SemanticSuggestion> {
|
) -> Vec<Suggestion> {
|
||||||
let prefix_str = prefix.as_ref();
|
let prefix_str = String::from_utf8_lossy(&prefix).to_string();
|
||||||
let start_with_backquote = prefix_str.starts_with('`');
|
let mut search_dirs: Vec<String> = vec![];
|
||||||
let end_with_backquote = prefix_str.ends_with('`');
|
let (base_dir, mut partial) = partial_from(&prefix_str);
|
||||||
let prefix_str = prefix_str.replace('`', "");
|
let mut is_current_folder = false;
|
||||||
// e.g. `./`, `..\`, `/`
|
|
||||||
let not_lib_dirs = prefix_str
|
|
||||||
.chars()
|
|
||||||
.find(|c| *c != '.')
|
|
||||||
.is_some_and(is_separator);
|
|
||||||
let mut search_dirs: Vec<PathBuf> = vec![];
|
|
||||||
|
|
||||||
let (base, partial) = if let Some((parent, remain)) = prefix_str.rsplit_once(is_separator) {
|
|
||||||
// If prefix_str is only a word we want to search in the current dir.
|
|
||||||
// "/xx" should be split to "/" and "xx".
|
|
||||||
if parent.is_empty() {
|
|
||||||
(MAIN_SEPARATOR_STR, remain)
|
|
||||||
} else {
|
|
||||||
(parent, remain)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
(".", prefix_str.as_str())
|
|
||||||
};
|
|
||||||
let base_dir = base.replace(is_separator, MAIN_SEPARATOR_STR);
|
|
||||||
|
|
||||||
// Fetch the lib dirs
|
// Fetch the lib dirs
|
||||||
// NOTE: 2 ways to setup `NU_LIB_DIRS`
|
let lib_dirs: Vec<String> =
|
||||||
// 1. `const NU_LIB_DIRS = [paths]`, equal to `nu -I paths`
|
if let Some(lib_dirs) = self.engine_state.get_env_var("NU_LIB_DIRS") {
|
||||||
// 2. `$env.NU_LIB_DIRS = [paths]`
|
|
||||||
let const_lib_dirs = working_set
|
|
||||||
.find_variable(b"$NU_LIB_DIRS")
|
|
||||||
.and_then(|vid| working_set.get_variable(vid).const_val.as_ref());
|
|
||||||
let env_lib_dirs = working_set.get_env_var("NU_LIB_DIRS");
|
|
||||||
let lib_dirs: HashSet<PathBuf> = [const_lib_dirs, env_lib_dirs]
|
|
||||||
.into_iter()
|
|
||||||
.flatten()
|
|
||||||
.flat_map(|lib_dirs| {
|
|
||||||
lib_dirs
|
lib_dirs
|
||||||
.as_list()
|
.as_list()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flat_map(|it| it.iter().filter_map(|x| x.to_path().ok()))
|
.flat_map(|it| {
|
||||||
.map(expand_tilde)
|
it.iter().map(|x| {
|
||||||
})
|
x.as_path()
|
||||||
.collect();
|
.expect("internal error: failed to convert lib path")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.map(|it| {
|
||||||
|
it.into_os_string()
|
||||||
|
.into_string()
|
||||||
|
.expect("internal error: failed to convert OS path")
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
vec![]
|
||||||
|
};
|
||||||
|
|
||||||
// Check if the base_dir is a folder
|
// Check if the base_dir is a folder
|
||||||
let cwd = working_set.permanent_state.cwd(None);
|
if base_dir != format!(".{}", SEP) {
|
||||||
if base_dir != "." {
|
// Add the base dir into the directories to be searched
|
||||||
let expanded_base_dir = expand_tilde(&base_dir);
|
search_dirs.push(base_dir.clone());
|
||||||
let is_base_dir_relative = expanded_base_dir.is_relative();
|
|
||||||
// Search in base_dir as well as lib_dirs.
|
// Reset the partial adding the basic dir back
|
||||||
// After expanded, base_dir can be a relative path or absolute path.
|
// in order to make the span replace work properly
|
||||||
// If relative, we join "current working dir" with it to get subdirectory and add to search_dirs.
|
let mut base_dir_partial = base_dir;
|
||||||
// If absolute, we add it to search_dirs.
|
base_dir_partial.push_str(&partial);
|
||||||
if let Ok(mut cwd) = cwd {
|
|
||||||
if is_base_dir_relative {
|
partial = base_dir_partial;
|
||||||
cwd.push(&base_dir);
|
|
||||||
search_dirs.push(cwd.into_std_path_buf());
|
|
||||||
} else {
|
|
||||||
search_dirs.push(expanded_base_dir);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !not_lib_dirs {
|
|
||||||
search_dirs.extend(lib_dirs.into_iter().map(|mut dir| {
|
|
||||||
dir.push(&base_dir);
|
|
||||||
dir
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
if let Ok(cwd) = cwd {
|
// Fetch the current folder
|
||||||
search_dirs.push(cwd.into_std_path_buf());
|
let current_folder = if let Some(d) = self.engine_state.get_env_var("PWD") {
|
||||||
}
|
match d.as_string() {
|
||||||
if !not_lib_dirs {
|
Ok(s) => s,
|
||||||
search_dirs.extend(lib_dirs);
|
Err(_) => "".to_string(),
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
"".to_string()
|
||||||
|
};
|
||||||
|
is_current_folder = true;
|
||||||
|
|
||||||
|
// Add the current folder and the lib dirs into the
|
||||||
|
// directories to be searched
|
||||||
|
search_dirs.push(current_folder);
|
||||||
|
search_dirs.extend(lib_dirs);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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 mut completions = file_path_completion(
|
let output: Vec<Suggestion> = search_dirs
|
||||||
span,
|
|
||||||
partial,
|
|
||||||
&search_dirs
|
|
||||||
.iter()
|
|
||||||
.filter_map(|d| d.to_str())
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
options,
|
|
||||||
working_set.permanent_state,
|
|
||||||
stack,
|
|
||||||
);
|
|
||||||
|
|
||||||
if self.std_virtual_path {
|
|
||||||
let mut matcher = NuMatcher::new(partial, options);
|
|
||||||
let base_dir = surround_remove(&base_dir);
|
|
||||||
if base_dir == "." {
|
|
||||||
let surround_prefix = partial
|
|
||||||
.chars()
|
|
||||||
.take_while(|c| "`'\"".contains(*c))
|
|
||||||
.collect::<String>();
|
|
||||||
for path in ["std", "std-rfc"] {
|
|
||||||
let path = format!("{surround_prefix}{path}");
|
|
||||||
matcher.add(
|
|
||||||
path.clone(),
|
|
||||||
FileSuggestion {
|
|
||||||
span,
|
|
||||||
path,
|
|
||||||
style: None,
|
|
||||||
is_dir: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else if let Some(VirtualPath::Dir(sub_paths)) =
|
|
||||||
working_set.find_virtual_path(&base_dir)
|
|
||||||
{
|
|
||||||
for sub_vp_id in sub_paths {
|
|
||||||
let (path, sub_vp) = working_set.get_virtual_path(*sub_vp_id);
|
|
||||||
let path = path
|
|
||||||
.strip_prefix(&format!("{base_dir}/"))
|
|
||||||
.unwrap_or(path)
|
|
||||||
.to_string();
|
|
||||||
matcher.add(
|
|
||||||
path.clone(),
|
|
||||||
FileSuggestion {
|
|
||||||
path,
|
|
||||||
span,
|
|
||||||
style: None,
|
|
||||||
is_dir: matches!(sub_vp, VirtualPath::Dir(_)),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
completions.extend(matcher.results());
|
|
||||||
}
|
|
||||||
|
|
||||||
completions
|
|
||||||
.into_iter()
|
.into_iter()
|
||||||
// Different base dir, so we list the .nu files or folders
|
.flat_map(|it| {
|
||||||
.filter(|it| {
|
file_path_completion(span, &partial, &it, options)
|
||||||
// for paths with spaces in them
|
.into_iter()
|
||||||
let path = it.path.trim_end_matches('`');
|
.filter(|it| {
|
||||||
path.ends_with(".nu") || it.is_dir
|
// Different base dir, so we list the .nu files or folders
|
||||||
|
if !is_current_folder {
|
||||||
|
it.1.ends_with(".nu") || it.1.ends_with(SEP)
|
||||||
|
} else {
|
||||||
|
// Lib dirs, so we filter only the .nu files
|
||||||
|
it.1.ends_with(".nu")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map(move |x| Suggestion {
|
||||||
|
value: x.1,
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
|
span: reedline::Span {
|
||||||
|
start: x.0.start - offset,
|
||||||
|
end: x.0.end - offset,
|
||||||
|
},
|
||||||
|
append_whitespace: true,
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.map(|x| {
|
.collect();
|
||||||
let append_whitespace = !x.is_dir && (!start_with_backquote || end_with_backquote);
|
|
||||||
// Re-calculate the span to replace
|
output
|
||||||
let mut span_offset = 0;
|
}
|
||||||
let mut value = x.path.to_string();
|
|
||||||
// Complete only the last path component
|
fn get_sort_by(&self) -> SortBy {
|
||||||
if base_dir == MAIN_SEPARATOR_STR {
|
SortBy::LevenshteinDistance
|
||||||
span_offset = base_dir.len()
|
|
||||||
} else if base_dir != "." {
|
|
||||||
span_offset = base_dir.len() + 1
|
|
||||||
}
|
|
||||||
// Retain only one '`'
|
|
||||||
if start_with_backquote {
|
|
||||||
value = value.trim_start_matches('`').to_string();
|
|
||||||
span_offset += 1;
|
|
||||||
}
|
|
||||||
// Add the backquote back
|
|
||||||
if end_with_backquote && !value.ends_with('`') {
|
|
||||||
value.push('`');
|
|
||||||
}
|
|
||||||
let end = x.span.end - offset;
|
|
||||||
let start = std::cmp::min(end, x.span.start - offset + span_offset);
|
|
||||||
SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value,
|
|
||||||
style: x.style,
|
|
||||||
span: reedline::Span { start, end },
|
|
||||||
append_whitespace,
|
|
||||||
..Suggestion::default()
|
|
||||||
},
|
|
||||||
kind: Some(SuggestionKind::Module),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,112 +0,0 @@
|
|||||||
use crate::completions::{
|
|
||||||
Completer, CompletionOptions, SemanticSuggestion, SuggestionKind,
|
|
||||||
completion_common::surround_remove, completion_options::NuMatcher,
|
|
||||||
};
|
|
||||||
use nu_protocol::{
|
|
||||||
ModuleId, Span,
|
|
||||||
engine::{Stack, StateWorkingSet},
|
|
||||||
};
|
|
||||||
use reedline::Suggestion;
|
|
||||||
|
|
||||||
pub struct ExportableCompletion<'a> {
|
|
||||||
pub module_id: ModuleId,
|
|
||||||
pub temp_working_set: Option<StateWorkingSet<'a>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// If name contains space, wrap it in quotes
|
|
||||||
fn wrapped_name(name: String) -> String {
|
|
||||||
if !name.contains(' ') {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
if name.contains('\'') {
|
|
||||||
format!("\"{}\"", name.replace('"', r#"\""#))
|
|
||||||
} else {
|
|
||||||
format!("'{name}'")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Completer for ExportableCompletion<'_> {
|
|
||||||
fn fetch(
|
|
||||||
&mut self,
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
_stack: &Stack,
|
|
||||||
prefix: impl AsRef<str>,
|
|
||||||
span: Span,
|
|
||||||
offset: usize,
|
|
||||||
options: &CompletionOptions,
|
|
||||||
) -> Vec<SemanticSuggestion> {
|
|
||||||
let mut matcher = NuMatcher::<()>::new(surround_remove(prefix.as_ref()), options);
|
|
||||||
let mut results = Vec::new();
|
|
||||||
let span = reedline::Span {
|
|
||||||
start: span.start - offset,
|
|
||||||
end: span.end - offset,
|
|
||||||
};
|
|
||||||
// TODO: use matcher.add_lazy to lazy evaluate an item if it matches the prefix
|
|
||||||
let mut add_suggestion = |value: String,
|
|
||||||
description: Option<String>,
|
|
||||||
extra: Option<Vec<String>>,
|
|
||||||
kind: SuggestionKind| {
|
|
||||||
results.push(SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value,
|
|
||||||
span,
|
|
||||||
description,
|
|
||||||
extra,
|
|
||||||
..Suggestion::default()
|
|
||||||
},
|
|
||||||
kind: Some(kind),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
let working_set = self.temp_working_set.as_ref().unwrap_or(working_set);
|
|
||||||
let module = working_set.get_module(self.module_id);
|
|
||||||
|
|
||||||
for (name, decl_id) in &module.decls {
|
|
||||||
let name = String::from_utf8_lossy(name).to_string();
|
|
||||||
if matcher.matches(&name) {
|
|
||||||
let cmd = working_set.get_decl(*decl_id);
|
|
||||||
add_suggestion(
|
|
||||||
wrapped_name(name),
|
|
||||||
Some(cmd.description().to_string()),
|
|
||||||
None,
|
|
||||||
// `None` here avoids arguments being expanded by snippet edit style for lsp
|
|
||||||
SuggestionKind::Command(cmd.command_type(), None),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (name, module_id) in &module.submodules {
|
|
||||||
let name = String::from_utf8_lossy(name).to_string();
|
|
||||||
if matcher.matches(&name) {
|
|
||||||
let comments = working_set.get_module_comments(*module_id).map(|spans| {
|
|
||||||
spans
|
|
||||||
.iter()
|
|
||||||
.map(|sp| {
|
|
||||||
String::from_utf8_lossy(working_set.get_span_contents(*sp)).into()
|
|
||||||
})
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
});
|
|
||||||
add_suggestion(
|
|
||||||
wrapped_name(name),
|
|
||||||
Some("Submodule".into()),
|
|
||||||
comments,
|
|
||||||
SuggestionKind::Module,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (name, var_id) in &module.constants {
|
|
||||||
let name = String::from_utf8_lossy(name).to_string();
|
|
||||||
if matcher.matches(&name) {
|
|
||||||
let var = working_set.get_variable(*var_id);
|
|
||||||
add_suggestion(
|
|
||||||
wrapped_name(name),
|
|
||||||
var.const_val
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|v| v.clone().coerce_into_string().ok()),
|
|
||||||
None,
|
|
||||||
SuggestionKind::Variable,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
results
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,71 +1,80 @@
|
|||||||
use crate::completions::{
|
use crate::completions::{Completer, CompletionOptions};
|
||||||
Completer, CompletionOptions,
|
|
||||||
completion_common::{AdjustView, adjust_if_intermediate, complete_item},
|
|
||||||
};
|
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
Span,
|
engine::{EngineState, StateWorkingSet},
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
levenshtein_distance, Span,
|
||||||
};
|
};
|
||||||
use reedline::Suggestion;
|
use reedline::Suggestion;
|
||||||
use std::path::Path;
|
use std::path::{is_separator, Path};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use super::{SemanticSuggestion, SuggestionKind, completion_common::FileSuggestion};
|
const SEP: char = std::path::MAIN_SEPARATOR;
|
||||||
|
|
||||||
pub struct FileCompletion;
|
#[derive(Clone)]
|
||||||
|
pub struct FileCompletion {
|
||||||
|
engine_state: Arc<EngineState>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FileCompletion {
|
||||||
|
pub fn new(engine_state: Arc<EngineState>) -> Self {
|
||||||
|
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: impl AsRef<str>,
|
|
||||||
span: Span,
|
span: Span,
|
||||||
offset: usize,
|
offset: 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.as_ref(), 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,
|
value: x.1,
|
||||||
working_set.permanent_state,
|
description: None,
|
||||||
stack,
|
extra: None,
|
||||||
)
|
|
||||||
.into_iter()
|
|
||||||
.map(move |x| SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value: x.path,
|
|
||||||
style: x.style,
|
|
||||||
span: reedline::Span {
|
span: reedline::Span {
|
||||||
start: x.span.start - offset,
|
start: x.0.start - offset,
|
||||||
end: x.span.end - offset,
|
end: x.0.end - offset,
|
||||||
},
|
},
|
||||||
..Suggestion::default()
|
append_whitespace: false,
|
||||||
},
|
})
|
||||||
kind: Some(if x.is_dir {
|
.collect();
|
||||||
SuggestionKind::Directory
|
|
||||||
} else {
|
|
||||||
SuggestionKind::File
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
.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() {
|
||||||
@@ -85,13 +94,97 @@ 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,
|
||||||
cwds: &[impl AsRef<str>],
|
cwd: &str,
|
||||||
options: &CompletionOptions,
|
options: &CompletionOptions,
|
||||||
engine_state: &EngineState,
|
) -> Vec<(nu_protocol::Span, String)> {
|
||||||
stack: &Stack,
|
let original_input = partial;
|
||||||
) -> Vec<FileSuggestion> {
|
let (base_dir_name, partial) = partial_from(partial);
|
||||||
complete_item(false, span, partial, cwds, 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 {
|
||||||
|
// Check for case sensitive
|
||||||
|
if !options.case_sensitive {
|
||||||
|
return options
|
||||||
|
.match_algorithm
|
||||||
|
.matches_str(&from.to_ascii_lowercase(), &partial.to_ascii_lowercase());
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,58 +1,86 @@
|
|||||||
use crate::completions::{
|
use crate::completions::{Completer, CompletionOptions};
|
||||||
Completer, CompletionOptions, SemanticSuggestion, SuggestionKind, completion_options::NuMatcher,
|
|
||||||
};
|
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
DeclId, Span,
|
ast::{Expr, Expression},
|
||||||
engine::{Stack, StateWorkingSet},
|
engine::StateWorkingSet,
|
||||||
|
Span,
|
||||||
};
|
};
|
||||||
|
|
||||||
use reedline::Suggestion;
|
use reedline::Suggestion;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct FlagCompletion {
|
pub struct FlagCompletion {
|
||||||
pub decl_id: DeclId,
|
expression: Expression,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FlagCompletion {
|
||||||
|
pub fn new(expression: Expression) -> Self {
|
||||||
|
Self { expression }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Completer for FlagCompletion {
|
impl Completer for FlagCompletion {
|
||||||
fn fetch(
|
fn fetch(
|
||||||
&mut self,
|
&mut self,
|
||||||
working_set: &StateWorkingSet,
|
working_set: &StateWorkingSet,
|
||||||
_stack: &Stack,
|
prefix: Vec<u8>,
|
||||||
prefix: impl AsRef<str>,
|
|
||||||
span: Span,
|
span: Span,
|
||||||
offset: usize,
|
offset: usize,
|
||||||
|
_: usize,
|
||||||
options: &CompletionOptions,
|
options: &CompletionOptions,
|
||||||
) -> Vec<SemanticSuggestion> {
|
) -> Vec<Suggestion> {
|
||||||
let mut matcher = NuMatcher::new(prefix, options);
|
// Check if it's a flag
|
||||||
let mut add_suggestion = |value: String, description: String| {
|
if let Expr::Call(call) = &self.expression.expr {
|
||||||
matcher.add_semantic_suggestion(SemanticSuggestion {
|
let decl = working_set.get_decl(call.decl_id);
|
||||||
suggestion: Suggestion {
|
let sig = decl.signature();
|
||||||
value,
|
|
||||||
description: Some(description),
|
|
||||||
span: reedline::Span {
|
|
||||||
start: span.start - offset,
|
|
||||||
end: span.end - offset,
|
|
||||||
},
|
|
||||||
append_whitespace: true,
|
|
||||||
..Suggestion::default()
|
|
||||||
},
|
|
||||||
kind: Some(SuggestionKind::Flag),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
let decl = working_set.get_decl(self.decl_id);
|
let mut output = vec![];
|
||||||
let sig = decl.signature();
|
|
||||||
for named in &sig.named {
|
for named in &sig.named {
|
||||||
if let Some(short) = named.short {
|
let flag_desc = &named.desc;
|
||||||
let mut name = String::from("-");
|
if let Some(short) = named.short {
|
||||||
name.push(short);
|
let mut named = vec![0; short.len_utf8()];
|
||||||
add_suggestion(name, named.desc.clone());
|
short.encode_utf8(&mut named);
|
||||||
|
named.insert(0, b'-');
|
||||||
|
|
||||||
|
if options.match_algorithm.matches_u8(&named, &prefix) {
|
||||||
|
output.push(Suggestion {
|
||||||
|
value: String::from_utf8_lossy(&named).to_string(),
|
||||||
|
description: Some(flag_desc.to_string()),
|
||||||
|
extra: None,
|
||||||
|
span: reedline::Span {
|
||||||
|
start: span.start - offset,
|
||||||
|
end: span.end - offset,
|
||||||
|
},
|
||||||
|
append_whitespace: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if named.long.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut named = named.long.as_bytes().to_vec();
|
||||||
|
named.insert(0, b'-');
|
||||||
|
named.insert(0, b'-');
|
||||||
|
|
||||||
|
if options.match_algorithm.matches_u8(&named, &prefix) {
|
||||||
|
output.push(Suggestion {
|
||||||
|
value: String::from_utf8_lossy(&named).to_string(),
|
||||||
|
description: Some(flag_desc.to_string()),
|
||||||
|
extra: None,
|
||||||
|
span: reedline::Span {
|
||||||
|
start: span.start - offset,
|
||||||
|
end: span.end - offset,
|
||||||
|
},
|
||||||
|
append_whitespace: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if named.long.is_empty() {
|
return output;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
add_suggestion(format!("--{}", named.long), named.desc.clone());
|
|
||||||
}
|
}
|
||||||
matcher.results()
|
|
||||||
|
vec![]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,23 @@
|
|||||||
mod attribute_completions;
|
|
||||||
mod base;
|
mod base;
|
||||||
mod cell_path_completions;
|
|
||||||
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 exportable_completions;
|
|
||||||
mod file_completions;
|
mod file_completions;
|
||||||
mod flag_completions;
|
mod flag_completions;
|
||||||
mod operator_completions;
|
|
||||||
mod variable_completions;
|
mod variable_completions;
|
||||||
|
|
||||||
pub use attribute_completions::{AttributableCompletion, AttributeCompletion};
|
pub use base::Completer;
|
||||||
pub use base::{Completer, SemanticSuggestion, SuggestionKind};
|
|
||||||
pub use cell_path_completions::CellPathCompletion;
|
|
||||||
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 exportable_completions::ExportableCompletion;
|
pub use file_completions::{
|
||||||
pub use file_completions::{FileCompletion, file_path_completion};
|
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;
|
||||||
|
|||||||
@@ -1,277 +0,0 @@
|
|||||||
use crate::completions::{
|
|
||||||
Completer, CompletionOptions, SemanticSuggestion, SuggestionKind, completion_options::NuMatcher,
|
|
||||||
};
|
|
||||||
use nu_protocol::{
|
|
||||||
ENV_VARIABLE_ID, Span, Type, Value,
|
|
||||||
ast::{self, Comparison, Expr, Expression},
|
|
||||||
engine::{Stack, StateWorkingSet},
|
|
||||||
};
|
|
||||||
use reedline::Suggestion;
|
|
||||||
use strum::{EnumMessage, IntoEnumIterator};
|
|
||||||
|
|
||||||
use super::cell_path_completions::eval_cell_path;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct OperatorCompletion<'a> {
|
|
||||||
pub left_hand_side: &'a Expression,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct OperatorItem {
|
|
||||||
pub symbols: String,
|
|
||||||
pub description: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn operator_to_item<T: EnumMessage + AsRef<str>>(op: T) -> OperatorItem {
|
|
||||||
OperatorItem {
|
|
||||||
symbols: op.as_ref().into(),
|
|
||||||
description: op.get_message().unwrap_or_default().into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn common_comparison_ops() -> Vec<OperatorItem> {
|
|
||||||
vec![
|
|
||||||
operator_to_item(Comparison::In),
|
|
||||||
operator_to_item(Comparison::NotIn),
|
|
||||||
operator_to_item(Comparison::Equal),
|
|
||||||
operator_to_item(Comparison::NotEqual),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn all_ops_for_immutable() -> Vec<OperatorItem> {
|
|
||||||
ast::Comparison::iter()
|
|
||||||
.map(operator_to_item)
|
|
||||||
.chain(ast::Math::iter().map(operator_to_item))
|
|
||||||
.chain(ast::Boolean::iter().map(operator_to_item))
|
|
||||||
.chain(ast::Bits::iter().map(operator_to_item))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collection_comparison_ops() -> Vec<OperatorItem> {
|
|
||||||
let mut ops = common_comparison_ops();
|
|
||||||
ops.push(operator_to_item(Comparison::Has));
|
|
||||||
ops.push(operator_to_item(Comparison::NotHas));
|
|
||||||
ops
|
|
||||||
}
|
|
||||||
|
|
||||||
fn number_comparison_ops() -> Vec<OperatorItem> {
|
|
||||||
Comparison::iter()
|
|
||||||
.filter(|op| {
|
|
||||||
!matches!(
|
|
||||||
op,
|
|
||||||
Comparison::RegexMatch
|
|
||||||
| Comparison::NotRegexMatch
|
|
||||||
| Comparison::StartsWith
|
|
||||||
| Comparison::EndsWith
|
|
||||||
| Comparison::Has
|
|
||||||
| Comparison::NotHas
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.map(operator_to_item)
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn math_ops() -> Vec<OperatorItem> {
|
|
||||||
ast::Math::iter()
|
|
||||||
.filter(|op| !matches!(op, ast::Math::Concatenate | ast::Math::Pow))
|
|
||||||
.map(operator_to_item)
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bit_ops() -> Vec<OperatorItem> {
|
|
||||||
ast::Bits::iter().map(operator_to_item).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn all_assignment_ops() -> Vec<OperatorItem> {
|
|
||||||
ast::Assignment::iter().map(operator_to_item).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn numeric_assignment_ops() -> Vec<OperatorItem> {
|
|
||||||
ast::Assignment::iter()
|
|
||||||
.filter(|op| !matches!(op, ast::Assignment::ConcatenateAssign))
|
|
||||||
.map(operator_to_item)
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn concat_assignment_ops() -> Vec<OperatorItem> {
|
|
||||||
vec![
|
|
||||||
operator_to_item(ast::Assignment::Assign),
|
|
||||||
operator_to_item(ast::Assignment::ConcatenateAssign),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn valid_int_ops() -> Vec<OperatorItem> {
|
|
||||||
let mut ops = valid_float_ops();
|
|
||||||
ops.extend(bit_ops());
|
|
||||||
ops
|
|
||||||
}
|
|
||||||
|
|
||||||
fn valid_float_ops() -> Vec<OperatorItem> {
|
|
||||||
let mut ops = valid_value_with_unit_ops();
|
|
||||||
ops.push(operator_to_item(ast::Math::Pow));
|
|
||||||
ops
|
|
||||||
}
|
|
||||||
|
|
||||||
fn valid_string_ops() -> Vec<OperatorItem> {
|
|
||||||
let mut ops: Vec<OperatorItem> = Comparison::iter().map(operator_to_item).collect();
|
|
||||||
ops.push(operator_to_item(ast::Math::Concatenate));
|
|
||||||
ops.push(OperatorItem {
|
|
||||||
symbols: "like".into(),
|
|
||||||
description: Comparison::RegexMatch
|
|
||||||
.get_message()
|
|
||||||
.unwrap_or_default()
|
|
||||||
.into(),
|
|
||||||
});
|
|
||||||
ops.push(OperatorItem {
|
|
||||||
symbols: "not-like".into(),
|
|
||||||
description: Comparison::NotRegexMatch
|
|
||||||
.get_message()
|
|
||||||
.unwrap_or_default()
|
|
||||||
.into(),
|
|
||||||
});
|
|
||||||
ops
|
|
||||||
}
|
|
||||||
|
|
||||||
fn valid_list_ops() -> Vec<OperatorItem> {
|
|
||||||
let mut ops = collection_comparison_ops();
|
|
||||||
ops.push(operator_to_item(ast::Math::Concatenate));
|
|
||||||
ops
|
|
||||||
}
|
|
||||||
|
|
||||||
fn valid_binary_ops() -> Vec<OperatorItem> {
|
|
||||||
let mut ops = number_comparison_ops();
|
|
||||||
ops.extend(bit_ops());
|
|
||||||
ops.push(operator_to_item(ast::Math::Concatenate));
|
|
||||||
ops
|
|
||||||
}
|
|
||||||
|
|
||||||
fn valid_bool_ops() -> Vec<OperatorItem> {
|
|
||||||
let mut ops: Vec<OperatorItem> = ast::Boolean::iter().map(operator_to_item).collect();
|
|
||||||
ops.extend(common_comparison_ops());
|
|
||||||
ops
|
|
||||||
}
|
|
||||||
|
|
||||||
fn valid_value_with_unit_ops() -> Vec<OperatorItem> {
|
|
||||||
let mut ops = number_comparison_ops();
|
|
||||||
ops.extend(math_ops());
|
|
||||||
ops
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ops_by_value(value: &Value, mutable: bool) -> Vec<OperatorItem> {
|
|
||||||
let mut ops = match value {
|
|
||||||
Value::Int { .. } => valid_int_ops(),
|
|
||||||
Value::Float { .. } => valid_float_ops(),
|
|
||||||
Value::String { .. } => valid_string_ops(),
|
|
||||||
Value::Binary { .. } => valid_binary_ops(),
|
|
||||||
Value::Bool { .. } => valid_bool_ops(),
|
|
||||||
Value::Date { .. } => number_comparison_ops(),
|
|
||||||
Value::Filesize { .. } | Value::Duration { .. } => valid_value_with_unit_ops(),
|
|
||||||
Value::Range { .. } | Value::Record { .. } => collection_comparison_ops(),
|
|
||||||
Value::List { .. } => valid_list_ops(),
|
|
||||||
_ => all_ops_for_immutable(),
|
|
||||||
};
|
|
||||||
if mutable {
|
|
||||||
ops.extend(match value {
|
|
||||||
Value::Int { .. }
|
|
||||||
| Value::Float { .. }
|
|
||||||
| Value::Filesize { .. }
|
|
||||||
| Value::Duration { .. } => numeric_assignment_ops(),
|
|
||||||
Value::String { .. } | Value::Binary { .. } | Value::List { .. } => {
|
|
||||||
concat_assignment_ops()
|
|
||||||
}
|
|
||||||
Value::Bool { .. }
|
|
||||||
| Value::Date { .. }
|
|
||||||
| Value::Range { .. }
|
|
||||||
| Value::Record { .. } => vec![operator_to_item(ast::Assignment::Assign)],
|
|
||||||
_ => all_assignment_ops(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
ops
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_expression_mutable(expr: &Expr, working_set: &StateWorkingSet) -> bool {
|
|
||||||
let Expr::FullCellPath(path) = expr else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let Expr::Var(id) = path.head.expr else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
if id == ENV_VARIABLE_ID {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
let var = working_set.get_variable(id);
|
|
||||||
var.mutable
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Completer for OperatorCompletion<'_> {
|
|
||||||
fn fetch(
|
|
||||||
&mut self,
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
stack: &Stack,
|
|
||||||
prefix: impl AsRef<str>,
|
|
||||||
span: Span,
|
|
||||||
offset: usize,
|
|
||||||
options: &CompletionOptions,
|
|
||||||
) -> Vec<SemanticSuggestion> {
|
|
||||||
let mut needs_assignment_ops = true;
|
|
||||||
// Complete according expression type
|
|
||||||
// TODO: type inference on self.left_hand_side to get more accurate completions
|
|
||||||
let mut possible_operations: Vec<OperatorItem> = match &self.left_hand_side.ty {
|
|
||||||
Type::Int | Type::Number => valid_int_ops(),
|
|
||||||
Type::Float => valid_float_ops(),
|
|
||||||
Type::String => valid_string_ops(),
|
|
||||||
Type::Binary => valid_binary_ops(),
|
|
||||||
Type::Bool => valid_bool_ops(),
|
|
||||||
Type::Date => number_comparison_ops(),
|
|
||||||
Type::Filesize | Type::Duration => valid_value_with_unit_ops(),
|
|
||||||
Type::Record(_) | Type::Range => collection_comparison_ops(),
|
|
||||||
Type::List(_) | Type::Table(_) => valid_list_ops(),
|
|
||||||
// Unknown type, resort to evaluated values
|
|
||||||
Type::Any => match &self.left_hand_side.expr {
|
|
||||||
Expr::FullCellPath(path) => {
|
|
||||||
// for `$ <tab>`
|
|
||||||
if matches!(path.head.expr, Expr::Garbage) {
|
|
||||||
return vec![];
|
|
||||||
}
|
|
||||||
let value =
|
|
||||||
eval_cell_path(working_set, stack, &path.head, &path.tail, path.head.span)
|
|
||||||
.unwrap_or_default();
|
|
||||||
let mutable = is_expression_mutable(&self.left_hand_side.expr, working_set);
|
|
||||||
// to avoid duplication
|
|
||||||
needs_assignment_ops = false;
|
|
||||||
ops_by_value(&value, mutable)
|
|
||||||
}
|
|
||||||
_ => all_ops_for_immutable(),
|
|
||||||
},
|
|
||||||
_ => common_comparison_ops(),
|
|
||||||
};
|
|
||||||
// If the left hand side is a variable, add assignment operators if mutable
|
|
||||||
if needs_assignment_ops && is_expression_mutable(&self.left_hand_side.expr, working_set) {
|
|
||||||
possible_operations.extend(match &self.left_hand_side.ty {
|
|
||||||
Type::Int | Type::Float | Type::Number => numeric_assignment_ops(),
|
|
||||||
Type::Filesize | Type::Duration => numeric_assignment_ops(),
|
|
||||||
Type::String | Type::Binary | Type::List(_) => concat_assignment_ops(),
|
|
||||||
Type::Any => all_assignment_ops(),
|
|
||||||
_ => vec![operator_to_item(ast::Assignment::Assign)],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut matcher = NuMatcher::new(prefix, options);
|
|
||||||
for OperatorItem {
|
|
||||||
symbols,
|
|
||||||
description,
|
|
||||||
} in possible_operations
|
|
||||||
{
|
|
||||||
matcher.add_semantic_suggestion(SemanticSuggestion {
|
|
||||||
suggestion: Suggestion {
|
|
||||||
value: symbols.to_owned(),
|
|
||||||
description: Some(description.to_owned()),
|
|
||||||
span: reedline::Span::new(span.start - offset, span.end - offset),
|
|
||||||
append_whitespace: true,
|
|
||||||
..Suggestion::default()
|
|
||||||
},
|
|
||||||
kind: Some(SuggestionKind::Operator),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
matcher.results()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,79 +1,292 @@
|
|||||||
use crate::completions::{Completer, CompletionOptions, SemanticSuggestion, SuggestionKind};
|
use crate::completions::{Completer, CompletionOptions};
|
||||||
|
use nu_engine::eval_variable;
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
Span, VarId,
|
engine::{EngineState, Stack, StateWorkingSet},
|
||||||
engine::{Stack, StateWorkingSet},
|
Span, Value,
|
||||||
};
|
};
|
||||||
|
|
||||||
use reedline::Suggestion;
|
use reedline::Suggestion;
|
||||||
|
use std::str;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use super::completion_options::NuMatcher;
|
#[derive(Clone)]
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
pub struct VariableCompletion;
|
impl VariableCompletion {
|
||||||
|
pub fn new(
|
||||||
|
engine_state: Arc<EngineState>,
|
||||||
|
stack: Stack,
|
||||||
|
var_context: (Vec<u8>, Vec<Vec<u8>>),
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
engine_state,
|
||||||
|
stack,
|
||||||
|
var_context,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Completer for VariableCompletion {
|
impl Completer for VariableCompletion {
|
||||||
fn fetch(
|
fn fetch(
|
||||||
&mut self,
|
&mut self,
|
||||||
working_set: &StateWorkingSet,
|
working_set: &StateWorkingSet,
|
||||||
_stack: &Stack,
|
prefix: Vec<u8>,
|
||||||
prefix: impl AsRef<str>,
|
|
||||||
span: Span,
|
span: Span,
|
||||||
offset: usize,
|
offset: usize,
|
||||||
|
_: usize,
|
||||||
options: &CompletionOptions,
|
options: &CompletionOptions,
|
||||||
) -> Vec<SemanticSuggestion> {
|
) -> Vec<Suggestion> {
|
||||||
let mut matcher = NuMatcher::new(prefix, options);
|
let mut output = vec![];
|
||||||
|
let builtins = ["$nu", "$in", "$env", "$nothing"];
|
||||||
|
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 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();
|
||||||
|
|
||||||
// Variable completion (e.g: $en<tab> to complete $env)
|
// Completions for the given variable
|
||||||
let builtins = ["$nu", "$in", "$env"];
|
if !var_str.is_empty() {
|
||||||
for builtin in builtins {
|
// Completion for $env.<tab>
|
||||||
matcher.add_semantic_suggestion(SemanticSuggestion {
|
if var_str.as_str() == "$env" {
|
||||||
suggestion: Suggestion {
|
let env_vars = self.stack.get_env_vars(&self.engine_state);
|
||||||
value: builtin.to_string(),
|
|
||||||
span: current_span,
|
// Return nested values
|
||||||
description: Some("reserved".into()),
|
if sublevels_count > 0 {
|
||||||
..Suggestion::default()
|
// Extract the target var ($env.<target-var>)
|
||||||
},
|
let target_var = self.var_context.1[0].clone();
|
||||||
kind: Some(SuggestionKind::Variable),
|
let target_var_str =
|
||||||
});
|
str::from_utf8(&target_var).unwrap_or_default().to_string();
|
||||||
|
|
||||||
|
// Everything after the target var is the nested level ($env.<target-var>.<nested_levels>...)
|
||||||
|
let nested_levels: Vec<Vec<u8>> =
|
||||||
|
self.var_context.1.clone().into_iter().skip(1).collect();
|
||||||
|
|
||||||
|
if let Some(val) = env_vars.get(&target_var_str) {
|
||||||
|
for suggestion in
|
||||||
|
nested_suggestions(val.clone(), nested_levels, current_span)
|
||||||
|
{
|
||||||
|
if options
|
||||||
|
.match_algorithm
|
||||||
|
.matches_u8(suggestion.value.as_bytes(), &prefix)
|
||||||
|
{
|
||||||
|
output.push(suggestion);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No nesting provided, return all env vars
|
||||||
|
for env_var in env_vars {
|
||||||
|
if options
|
||||||
|
.match_algorithm
|
||||||
|
.matches_u8(env_var.0.as_bytes(), &prefix)
|
||||||
|
{
|
||||||
|
output.push(Suggestion {
|
||||||
|
value: env_var.0,
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
|
span: current_span,
|
||||||
|
append_whitespace: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Completions for $nu.<tab>
|
||||||
|
if var_str.as_str() == "$nu" {
|
||||||
|
// Eval nu var
|
||||||
|
if let Ok(nuval) = eval_variable(
|
||||||
|
&self.engine_state,
|
||||||
|
&self.stack,
|
||||||
|
nu_protocol::NU_VARIABLE_ID,
|
||||||
|
nu_protocol::Span {
|
||||||
|
start: current_span.start,
|
||||||
|
end: current_span.end,
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
for suggestion in
|
||||||
|
nested_suggestions(nuval, self.var_context.1.clone(), current_span)
|
||||||
|
{
|
||||||
|
if options
|
||||||
|
.match_algorithm
|
||||||
|
.matches_u8(suggestion.value.as_bytes(), &prefix)
|
||||||
|
{
|
||||||
|
output.push(suggestion);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Completion other variable types
|
||||||
|
if let Some(var_id) = var_id {
|
||||||
|
// Extract the variable value from the stack
|
||||||
|
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 let Ok(value) = var {
|
||||||
|
for suggestion in
|
||||||
|
nested_suggestions(value, self.var_context.1.clone(), current_span)
|
||||||
|
{
|
||||||
|
if options
|
||||||
|
.match_algorithm
|
||||||
|
.matches_u8(suggestion.value.as_bytes(), &prefix)
|
||||||
|
{
|
||||||
|
output.push(suggestion);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut add_candidate = |name, var_id: &VarId| {
|
// Variable completion (e.g: $en<tab> to complete $env)
|
||||||
matcher.add_semantic_suggestion(SemanticSuggestion {
|
for builtin in builtins {
|
||||||
suggestion: Suggestion {
|
if options
|
||||||
value: String::from_utf8_lossy(name).to_string(),
|
.match_algorithm
|
||||||
|
.matches_u8(builtin.as_bytes(), &prefix)
|
||||||
|
{
|
||||||
|
output.push(Suggestion {
|
||||||
|
value: builtin.to_string(),
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
span: current_span,
|
span: current_span,
|
||||||
description: Some(working_set.get_variable(*var_id).ty.to_string()),
|
append_whitespace: false,
|
||||||
..Suggestion::default()
|
});
|
||||||
},
|
}
|
||||||
kind: Some(SuggestionKind::Variable),
|
}
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
// TODO: The following can be refactored (see find_commands_by_predicate() used in
|
// TODO: The following can be refactored (see find_commands_by_predicate() used in
|
||||||
// command_completions).
|
// command_completions).
|
||||||
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
|
||||||
for (name, var_id) in &overlay_frame.vars {
|
.active_overlays(&mut removed_overlays)
|
||||||
add_candidate(name, var_id);
|
.iter()
|
||||||
|
.rev()
|
||||||
|
{
|
||||||
|
for v in &overlay_frame.vars {
|
||||||
|
if options.match_algorithm.matches_u8(v.0, &prefix) {
|
||||||
|
output.push(Suggestion {
|
||||||
|
value: String::from_utf8_lossy(v.0).to_string(),
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
|
span: current_span,
|
||||||
|
append_whitespace: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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 (name, var_id) in &overlay_frame.vars {
|
for v in &overlay_frame.vars {
|
||||||
add_candidate(name, var_id);
|
if options.match_algorithm.matches_u8(v.0, &prefix) {
|
||||||
|
output.push(Suggestion {
|
||||||
|
value: String::from_utf8_lossy(v.0).to_string(),
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
|
span: current_span,
|
||||||
|
append_whitespace: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
matcher.results()
|
output.dedup(); // TODO: Removes only consecutive duplicates, is it intended?
|
||||||
|
|
||||||
|
output
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Find recursively the values for sublevels
|
||||||
|
// if no sublevels are set it returns the current value
|
||||||
|
fn nested_suggestions(
|
||||||
|
val: Value,
|
||||||
|
sublevels: Vec<Vec<u8>>,
|
||||||
|
current_span: reedline::Span,
|
||||||
|
) -> Vec<Suggestion> {
|
||||||
|
let mut output: Vec<Suggestion> = vec![];
|
||||||
|
let value = recursive_value(val, sublevels);
|
||||||
|
|
||||||
|
match value {
|
||||||
|
Value::Record {
|
||||||
|
cols,
|
||||||
|
vals: _,
|
||||||
|
span: _,
|
||||||
|
} => {
|
||||||
|
// Add all the columns as completion
|
||||||
|
for item in cols {
|
||||||
|
output.push(Suggestion {
|
||||||
|
value: item,
|
||||||
|
description: None,
|
||||||
|
extra: None,
|
||||||
|
span: current_span,
|
||||||
|
append_whitespace: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => output,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extracts the recursive value (e.g: $var.a.b.c)
|
||||||
|
fn recursive_value(val: Value, sublevels: Vec<Vec<u8>>) -> Value {
|
||||||
|
// Go to next sublevel
|
||||||
|
if let Some(next_sublevel) = sublevels.clone().into_iter().next() {
|
||||||
|
match val {
|
||||||
|
Value::Record {
|
||||||
|
cols,
|
||||||
|
vals,
|
||||||
|
span: _,
|
||||||
|
} => {
|
||||||
|
for item in cols.into_iter().zip(vals.into_iter()) {
|
||||||
|
// Check if index matches with sublevel
|
||||||
|
if item.0.as_bytes().to_vec() == next_sublevel {
|
||||||
|
// If matches try to fetch recursively the next
|
||||||
|
return recursive_value(item.1, sublevels.into_iter().skip(1).collect());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Current sublevel value not found
|
||||||
|
return Value::Nothing {
|
||||||
|
span: Span { start: 0, end: 0 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
_ => return val,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,196 +1,76 @@
|
|||||||
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::{ParseError, PluginRegistryFile, Spanned, engine::StateWorkingSet};
|
use nu_protocol::Spanned;
|
||||||
use nu_protocol::{
|
use nu_protocol::{HistoryFileFormat, PipelineData, Span};
|
||||||
PipelineData,
|
|
||||||
engine::{EngineState, Stack},
|
|
||||||
report_shell_error,
|
|
||||||
};
|
|
||||||
#[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, shell_error::io::IoError};
|
engine_state: &mut EngineState,
|
||||||
use std::path::Path;
|
stack: &mut Stack,
|
||||||
|
plugin_file: Option<Spanned<String>>,
|
||||||
|
storage_path: &str,
|
||||||
|
is_perf_true: bool,
|
||||||
|
) {
|
||||||
|
// 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();
|
||||||
|
if let Some(plugin_path) = plugin_path {
|
||||||
|
let plugin_filename = plugin_path.to_string_lossy().to_owned();
|
||||||
|
|
||||||
// Check and warn + abort if this is a .nu plugin file
|
if let Ok(contents) = std::fs::read(&plugin_path) {
|
||||||
if plugin_file
|
eval_source(
|
||||||
.as_ref()
|
engine_state,
|
||||||
.and_then(|p| Path::new(&p.item).extension())
|
stack,
|
||||||
.is_some_and(|ext| ext == "nu")
|
&contents,
|
||||||
{
|
&plugin_filename,
|
||||||
report_shell_error(
|
PipelineData::new(Span::new(0, 0)),
|
||||||
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();
|
if is_perf_true {
|
||||||
// Reading signatures from plugin registry file
|
info!("read_plugin_file {}:{}:{}", file!(), line!(), column!());
|
||||||
// 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
|
|
||||||
.get(engine_state)
|
|
||||||
);
|
|
||||||
|
|
||||||
start_time = std::time::Instant::now();
|
|
||||||
let plugin_path = engine_state.plugin_path.clone();
|
|
||||||
if let Some(plugin_path) = plugin_path {
|
|
||||||
// Open the plugin file
|
|
||||||
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 plugin_file.is_none() && migrate_old_plugin_file(engine_state) {
|
|
||||||
let Ok(file) = std::fs::File::open(&plugin_path) else {
|
|
||||||
log::warn!("Failed to load newly migrated plugin file");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
file
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
report_shell_error(
|
|
||||||
engine_state,
|
|
||||||
&ShellError::Io(IoError::new_internal_with_path(
|
|
||||||
err,
|
|
||||||
"Could not open plugin registry file",
|
|
||||||
nu_protocol::location!(),
|
|
||||||
plugin_path,
|
|
||||||
)),
|
|
||||||
);
|
|
||||||
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
|
|
||||||
.get(engine_state)
|
|
||||||
);
|
|
||||||
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
|
|
||||||
.get(engine_state)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,169 +80,41 @@ pub fn eval_config_contents(
|
|||||||
stack: &mut Stack,
|
stack: &mut Stack,
|
||||||
) {
|
) {
|
||||||
if config_path.exists() & config_path.is_file() {
|
if config_path.exists() & config_path.is_file() {
|
||||||
let config_filename = config_path.to_string_lossy();
|
let config_filename = config_path.to_string_lossy().to_owned();
|
||||||
|
|
||||||
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, shell_error::io::IoError,
|
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(|err| {
|
|
||||||
IoError::new_internal_with_path(
|
|
||||||
err,
|
|
||||||
"Could not create new plugin file",
|
|
||||||
nu_protocol::location!(),
|
|
||||||
new_plugin_file_path.clone(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.map_err(ShellError::from)
|
|
||||||
.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
|
|
||||||
.get(&engine_state)
|
|
||||||
);
|
|
||||||
true
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,101 +0,0 @@
|
|||||||
use log::info;
|
|
||||||
use nu_engine::eval_block;
|
|
||||||
use nu_parser::parse;
|
|
||||||
use nu_protocol::{
|
|
||||||
PipelineData, ShellError, Spanned, Value,
|
|
||||||
debugger::WithoutDebug,
|
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
|
||||||
report_error::report_compile_error,
|
|
||||||
report_parse_error, report_parse_warning,
|
|
||||||
};
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::util::print_pipeline;
|
|
||||||
|
|
||||||
#[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![],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
(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();
|
|
||||||
}
|
|
||||||
|
|
||||||
print_pipeline(engine_state, stack, pipeline, no_newline)?;
|
|
||||||
|
|
||||||
info!("evaluate {}:{}:{}", file!(), line!(), column!());
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -1,154 +1,139 @@
|
|||||||
use crate::util::{eval_source, print_pipeline};
|
use crate::util::{eval_source, report_error};
|
||||||
use log::{info, trace};
|
use log::info;
|
||||||
use nu_engine::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::{
|
||||||
PipelineData, ShellError, Span, Value,
|
ast::Call,
|
||||||
debugger::WithoutDebug,
|
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
engine::{EngineState, Stack, StateWorkingSet},
|
||||||
report_error::report_compile_error,
|
Config, PipelineData, Span, Value,
|
||||||
report_parse_error, report_parse_warning,
|
|
||||||
shell_error::io::*,
|
|
||||||
};
|
};
|
||||||
use std::{path::PathBuf, 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> {
|
is_perf_true: bool,
|
||||||
let cwd = engine_state.cwd_as_string(Some(stack))?;
|
) -> Result<()> {
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
|
||||||
let file_path = canonicalize_with(&path, cwd).map_err(|err| {
|
let file = std::fs::read(&path).into_diagnostic()?;
|
||||||
IoError::new_internal_with_path(
|
|
||||||
err.not_found_as(NotFound::File),
|
|
||||||
"Could not access file",
|
|
||||||
nu_protocol::location!(),
|
|
||||||
PathBuf::from(&path),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
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| {
|
|
||||||
IoError::new_internal_with_path(
|
|
||||||
err.not_found_as(NotFound::File),
|
|
||||||
"Could not read file",
|
|
||||||
nu_protocol::location!(),
|
|
||||||
file_path.clone(),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
engine_state.file = Some(file_path.clone());
|
|
||||||
|
|
||||||
let parent = file_path.parent().ok_or_else(|| {
|
|
||||||
IoError::new_internal_with_path(
|
|
||||||
ErrorKind::DirectoryNotFound,
|
|
||||||
"The file path does not have a parent",
|
|
||||||
nu_protocol::location!(),
|
|
||||||
file_path.clone(),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
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);
|
let mut working_set = StateWorkingSet::new(engine_state);
|
||||||
trace!("parsing file: {}", file_path_str);
|
trace!("parsing file: {}", path);
|
||||||
let block = parse(&mut working_set, Some(file_path_str), &file, false);
|
|
||||||
|
|
||||||
if let Some(warning) = working_set.parse_warnings.first() {
|
let _ = parse(&mut working_set, Some(&path), &file, false, &[]);
|
||||||
report_parse_warning(&working_set, warning);
|
|
||||||
}
|
|
||||||
|
|
||||||
// If any parse errors were found, report the first error and exit.
|
if working_set.find_decl(b"main", &Type::Any).is_some() {
|
||||||
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);
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Look for blocks whose name starts with "main" and replace it with the filename.
|
|
||||||
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.
|
|
||||||
engine_state.merge_delta(working_set.delta)?;
|
|
||||||
|
|
||||||
// Check if the file contains a main command.
|
|
||||||
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.
|
|
||||||
print_pipeline(engine_state, stack, pipeline, true)?;
|
|
||||||
|
|
||||||
// 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!());
|
if is_perf_true {
|
||||||
|
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);
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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::{EvaluateCommandsOpts, evaluate_commands};
|
|
||||||
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;
|
||||||
|
|||||||
724
crates/nu-cli/src/menus/description_menu.rs
Normal file
724
crates/nu-cli/src/menus/description_menu.rs
Normal file
@@ -0,0 +1,724 @@
|
|||||||
|
use {
|
||||||
|
nu_ansi_term::{ansi::RESET, Style},
|
||||||
|
reedline::{
|
||||||
|
menu_functions::string_difference, Completer, LineBuffer, Menu, MenuEvent, MenuTextStyle,
|
||||||
|
Painter, Suggestion,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// 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_else(|| "".to_string())
|
||||||
|
.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,
|
||||||
|
_line_buffer: &mut LineBuffer,
|
||||||
|
_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, line_buffer: &mut LineBuffer, completer: &mut dyn Completer) {
|
||||||
|
if self.only_buffer_difference {
|
||||||
|
if let Some(old_string) = &self.input {
|
||||||
|
let (start, input) = string_difference(line_buffer.get_buffer(), old_string);
|
||||||
|
if !input.is_empty() {
|
||||||
|
self.reset_position();
|
||||||
|
self.values = completer.complete(input, start);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let trimmed_buffer = line_buffer.get_buffer().replace('\n', " ");
|
||||||
|
self.values =
|
||||||
|
completer.complete(trimmed_buffer.as_str(), 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,
|
||||||
|
line_buffer: &mut LineBuffer,
|
||||||
|
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(line_buffer.get_buffer().to_string());
|
||||||
|
self.update_values(line_buffer, completer);
|
||||||
|
}
|
||||||
|
MenuEvent::Deactivate => self.active = false,
|
||||||
|
MenuEvent::Edit(_) => {
|
||||||
|
self.reset_position();
|
||||||
|
self.update_values(line_buffer, 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_else(|| "".to_string())
|
||||||
|
.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, line_buffer: &mut LineBuffer) {
|
||||||
|
if let Some(Suggestion { value, span, .. }) = self.get_value() {
|
||||||
|
let start = span.start.min(line_buffer.len());
|
||||||
|
let end = span.end.min(line_buffer.len());
|
||||||
|
|
||||||
|
let string_len = if let Some(example_index) = self.example_index {
|
||||||
|
let example = self
|
||||||
|
.examples
|
||||||
|
.get(example_index)
|
||||||
|
.expect("the example index is always checked");
|
||||||
|
|
||||||
|
line_buffer.replace(start..end, example);
|
||||||
|
example.len()
|
||||||
|
} else {
|
||||||
|
line_buffer.replace(start..end, &value);
|
||||||
|
value.len()
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut offset = line_buffer.insertion_point();
|
||||||
|
offset += string_len.saturating_sub(end.saturating_sub(start));
|
||||||
|
line_buffer.set_insertion_point(offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,77 +1,63 @@
|
|||||||
use nu_engine::documentation::{FormatterValue, HelpStyle, get_flags_section};
|
use nu_engine::documentation::get_flags_section;
|
||||||
use nu_protocol::{Config, engine::EngineState, levenshtein_distance};
|
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| match v {
|
long_desc.push_str(&get_flags_section(sig))
|
||||||
FormatterValue::DefaultValue(value) => {
|
|
||||||
value.to_parsable_string(", ", &self.config)
|
|
||||||
}
|
|
||||||
FormatterValue::CodeString(text) => text.to_string(),
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if !sig.required_positional.is_empty()
|
if !sig.required_positional.is_empty()
|
||||||
@@ -83,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
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,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()
|
||||||
@@ -133,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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,16 +1,15 @@
|
|||||||
use nu_engine::eval_block;
|
use nu_engine::eval_block;
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
BlockId, IntoPipelineData, Span, Value,
|
|
||||||
debugger::WithoutDebug,
|
|
||||||
engine::{EngineState, Stack},
|
engine::{EngineState, Stack},
|
||||||
|
IntoPipelineData, Span, Value,
|
||||||
};
|
};
|
||||||
use reedline::{Completer, Suggestion, menu_functions::parse_selection_char};
|
use reedline::{menu_functions::parse_selection_char, Completer, Suggestion};
|
||||||
use std::sync::Arc;
|
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,
|
||||||
}],
|
}],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -1,9 +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;
|
||||||
|
|
||||||
use crate::syntax_highlight::highlight_syntax;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct NuHighlight;
|
pub struct NuHighlight;
|
||||||
@@ -14,17 +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)
|
|
||||||
.switch(
|
|
||||||
"reject-garbage",
|
|
||||||
"Return an error if invalid syntax (garbage) was encountered",
|
|
||||||
Some('r'),
|
|
||||||
)
|
|
||||||
.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."
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,42 +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 reject_garbage = call.has_flag(engine_state, stack, "reject-garbage")?;
|
|
||||||
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 engine_state = Arc::new(engine_state.clone());
|
let highlighter = crate::NuHighlighter {
|
||||||
let stack = Arc::new(stack.clone());
|
engine_state,
|
||||||
|
config,
|
||||||
|
};
|
||||||
|
|
||||||
input.map(
|
input.map(
|
||||||
move |x| match x.coerce_into_string() {
|
move |x| match x.as_string() {
|
||||||
Ok(line) => {
|
Ok(line) => {
|
||||||
let result = highlight_syntax(&engine_state, &stack, &line, line.len());
|
let highlights = highlighter.highlight(&line, line.len());
|
||||||
|
|
||||||
let highlights = match (reject_garbage, result.found_garbage) {
|
Value::String {
|
||||||
(false, _) => result.text,
|
val: highlights.render_simple(),
|
||||||
(true, None) => result.text,
|
span: head,
|
||||||
(true, Some(span)) => {
|
}
|
||||||
let error = ShellError::OutsideSpannedLabeledError {
|
|
||||||
src: line,
|
|
||||||
error: "encountered invalid syntax while highlighting".into(),
|
|
||||||
msg: "invalid syntax".into(),
|
|
||||||
span,
|
|
||||||
};
|
|
||||||
return Value::error(error, head);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Value::string(highlights.render_simple(), head)
|
|
||||||
}
|
}
|
||||||
Err(err) => Value::error(err, head),
|
Err(err) => Value::Error { error: err },
|
||||||
},
|
},
|
||||||
signals,
|
ctrlc,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,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()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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,42 +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_table(
|
|
||||||
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_table(engine_state, stack, no_newline, to_stderr)?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(PipelineData::empty())
|
Ok(PipelineData::new(head))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn examples(&self) -> Vec<Example> {
|
fn examples(&self) -> Vec<Example> {
|
||||||
@@ -101,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,
|
|
||||||
},
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,50 +1,39 @@
|
|||||||
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>,
|
||||||
default_vi_insert_prompt_indicator: Option<String>,
|
default_vi_insert_prompt_indicator: Option<String>,
|
||||||
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,
|
}
|
||||||
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,
|
||||||
default_vi_insert_prompt_indicator: None,
|
default_vi_insert_prompt_indicator: None,
|
||||||
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,
|
|
||||||
engine_state,
|
|
||||||
stack,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,13 +41,8 @@ impl NushellPrompt {
|
|||||||
self.left_prompt_string = prompt_string;
|
self.left_prompt_string = prompt_string;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_prompt_right(
|
pub fn update_prompt_right(&mut self, prompt_string: Option<String>) {
|
||||||
&mut self,
|
|
||||||
prompt_string: Option<String>,
|
|
||||||
render_right_prompt_on_last_line: bool,
|
|
||||||
) {
|
|
||||||
self.right_prompt_string = prompt_string;
|
self.right_prompt_string = prompt_string;
|
||||||
self.render_right_prompt_on_last_line = render_right_prompt_on_last_line;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_prompt_indicator(&mut self, prompt_indicator_string: Option<String>) {
|
pub fn update_prompt_indicator(&mut self, prompt_indicator_string: Option<String>) {
|
||||||
@@ -84,7 +68,6 @@ impl NushellPrompt {
|
|||||||
prompt_indicator_string: Option<String>,
|
prompt_indicator_string: Option<String>,
|
||||||
prompt_multiline_indicator_string: Option<String>,
|
prompt_multiline_indicator_string: Option<String>,
|
||||||
prompt_vi: (Option<String>, Option<String>),
|
prompt_vi: (Option<String>, Option<String>),
|
||||||
render_right_prompt_on_last_line: bool,
|
|
||||||
) {
|
) {
|
||||||
let (prompt_vi_insert_string, prompt_vi_normal_string) = prompt_vi;
|
let (prompt_vi_insert_string, prompt_vi_normal_string) = prompt_vi;
|
||||||
|
|
||||||
@@ -95,12 +78,10 @@ impl NushellPrompt {
|
|||||||
|
|
||||||
self.default_vi_insert_prompt_indicator = prompt_vi_insert_string;
|
self.default_vi_insert_prompt_indicator = prompt_vi_insert_string;
|
||||||
self.default_vi_normal_prompt_indicator = prompt_vi_normal_string;
|
self.default_vi_normal_prompt_indicator = prompt_vi_normal_string;
|
||||||
|
|
||||||
self.render_right_prompt_on_last_line = render_right_prompt_on_last_line;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_wrapped_custom_string(&self, str: String) -> String {
|
fn default_wrapped_custom_string(&self, str: String) -> String {
|
||||||
format!("({str})")
|
format!("({})", str)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,32 +95,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 +108,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 +120,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(
|
||||||
@@ -205,8 +162,4 @@ impl Prompt for NushellPrompt {
|
|||||||
prefix, history_search.term
|
prefix, history_search.term
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn right_prompt_on_last_line(&self) -> bool {
|
|
||||||
self.render_right_prompt_on_last_line
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
|
use crate::util::report_error;
|
||||||
use crate::NushellPrompt;
|
use crate::NushellPrompt;
|
||||||
use log::{trace, warn};
|
use log::info;
|
||||||
use nu_engine::ClosureEvalOnce;
|
use nu_engine::eval_subexpression;
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
Config, PipelineData, Value,
|
engine::{EngineState, Stack, StateWorkingSet},
|
||||||
engine::{EngineState, Stack},
|
Config, PipelineData, Span, Value,
|
||||||
report_shell_error,
|
|
||||||
};
|
};
|
||||||
use reedline::Prompt;
|
use reedline::Prompt;
|
||||||
|
|
||||||
@@ -15,140 +15,146 @@ 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\\";
|
|
||||||
pub(crate) const POST_EXECUTION_MARKER_PREFIX: &str = "\x1b]133;D;";
|
|
||||||
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\\";
|
|
||||||
pub(crate) const VSCODE_PRE_EXECUTION_MARKER: &str = "\x1b]633;C\x1b\\";
|
|
||||||
//"\x1b]633;D;{}\x1b\\"
|
|
||||||
pub(crate) const VSCODE_POST_EXECUTION_MARKER_PREFIX: &str = "\x1b]633;D;";
|
|
||||||
pub(crate) const VSCODE_POST_EXECUTION_MARKER_SUFFIX: &str = "\x1b\\";
|
|
||||||
//"\x1b]633;E;{}\x1b\\"
|
|
||||||
pub(crate) const VSCODE_COMMANDLINE_MARKER_PREFIX: &str = "\x1b]633;E;";
|
|
||||||
pub(crate) const VSCODE_COMMANDLINE_MARKER_SUFFIX: &str = "\x1b\\";
|
|
||||||
// "\x1b]633;P;Cwd={}\x1b\\"
|
|
||||||
pub(crate) const VSCODE_CWD_PROPERTY_MARKER_PREFIX: &str = "\x1b]633;P;Cwd=";
|
|
||||||
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,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
engine_state: &EngineState,
|
engine_state: &EngineState,
|
||||||
stack: &mut Stack,
|
stack: &mut Stack,
|
||||||
|
is_perf_true: bool,
|
||||||
) -> Option<String> {
|
) -> Option<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::Block {
|
||||||
let result = ClosureEvalOnce::new(engine_state, stack, val.as_ref().clone())
|
val: block_id,
|
||||||
.run_with_input(PipelineData::Empty);
|
captures,
|
||||||
|
..
|
||||||
trace!(
|
} => {
|
||||||
"get_prompt_string (block) {}:{}:{}",
|
let block = engine_state.get_block(block_id);
|
||||||
file!(),
|
let mut stack = stack.captures_to_stack(&captures);
|
||||||
line!(),
|
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
|
||||||
column!()
|
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
|
||||||
);
|
);
|
||||||
|
if is_perf_true {
|
||||||
|
info!(
|
||||||
|
"get_prompt_string (block) {}:{}:{}",
|
||||||
|
file!(),
|
||||||
|
line!(),
|
||||||
|
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::String { .. } => Some(PipelineData::Value(v.clone(), None)),
|
Value::String { .. } => Some(PipelineData::Value(v.clone(), None)),
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
.and_then(|pipeline_data| {
|
.and_then(|pipeline_data| {
|
||||||
let output = pipeline_data.collect_string("", config).ok();
|
let output = pipeline_data.collect_string("", config).ok();
|
||||||
let ansi_output = output.map(|mut x| {
|
|
||||||
// Always reset the color at the start of the right prompt
|
|
||||||
// to ensure there is no ansi bleed over
|
|
||||||
if x.is_empty() && prompt == PROMPT_COMMAND_RIGHT {
|
|
||||||
x.insert_str(0, "\x1b[0m")
|
|
||||||
};
|
|
||||||
|
|
||||||
x
|
match output {
|
||||||
});
|
Some(mut x) => {
|
||||||
// Let's keep this for debugging purposes with nu --log-level warn
|
// Just remove the very last newline.
|
||||||
warn!("{}:{}:{} {:?}", file!(), line!(), column!(), ansi_output);
|
if x.ends_with('\n') {
|
||||||
|
x.pop();
|
||||||
|
}
|
||||||
|
|
||||||
ansi_output
|
if x.ends_with('\r') {
|
||||||
|
x.pop();
|
||||||
|
}
|
||||||
|
Some(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,
|
||||||
) {
|
is_perf_true: bool,
|
||||||
let configured_left_prompt_string =
|
) -> &'prompt dyn Prompt {
|
||||||
match get_prompt_string(PROMPT_COMMAND, config, engine_state, stack) {
|
let mut stack = stack.clone();
|
||||||
Some(s) => s,
|
|
||||||
None => "".to_string(),
|
let left_prompt_string = get_prompt_string(
|
||||||
};
|
PROMPT_COMMAND,
|
||||||
|
config,
|
||||||
|
engine_state,
|
||||||
|
&mut stack,
|
||||||
|
is_perf_true,
|
||||||
|
);
|
||||||
|
|
||||||
// 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,
|
||||||
|
is_perf_true,
|
||||||
|
);
|
||||||
|
|
||||||
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,
|
||||||
|
is_perf_true,
|
||||||
|
);
|
||||||
|
|
||||||
let prompt_multiline_string =
|
let prompt_multiline_string = get_prompt_string(
|
||||||
get_prompt_string(PROMPT_MULTILINE_INDICATOR, config, engine_state, stack);
|
PROMPT_MULTILINE_INDICATOR,
|
||||||
|
config,
|
||||||
|
engine_state,
|
||||||
|
&mut stack,
|
||||||
|
is_perf_true,
|
||||||
|
);
|
||||||
|
|
||||||
let prompt_vi_insert_string =
|
let prompt_vi_insert_string = get_prompt_string(
|
||||||
get_prompt_string(PROMPT_INDICATOR_VI_INSERT, config, engine_state, stack);
|
PROMPT_INDICATOR_VI_INSERT,
|
||||||
|
config,
|
||||||
|
engine_state,
|
||||||
|
&mut stack,
|
||||||
|
is_perf_true,
|
||||||
|
);
|
||||||
|
|
||||||
let prompt_vi_normal_string =
|
let prompt_vi_normal_string = get_prompt_string(
|
||||||
get_prompt_string(PROMPT_INDICATOR_VI_NORMAL, config, engine_state, stack);
|
PROMPT_INDICATOR_VI_NORMAL,
|
||||||
|
config,
|
||||||
|
engine_state,
|
||||||
|
&mut stack,
|
||||||
|
is_perf_true,
|
||||||
|
);
|
||||||
|
|
||||||
// apply the other indicators
|
// apply the other indicators
|
||||||
nu_prompt.update_all_prompt_strings(
|
nu_prompt.update_all_prompt_strings(
|
||||||
@@ -157,57 +163,12 @@ pub(crate) fn update_prompt(
|
|||||||
prompt_indicator_string,
|
prompt_indicator_string,
|
||||||
prompt_multiline_string,
|
prompt_multiline_string,
|
||||||
(prompt_vi_insert_string, prompt_vi_normal_string),
|
(prompt_vi_insert_string, prompt_vi_normal_string),
|
||||||
config.render_right_prompt_on_last_line,
|
|
||||||
);
|
);
|
||||||
trace!("update_prompt {}:{}:{}", file!(), line!(), column!());
|
|
||||||
}
|
let ret_val = nu_prompt as &dyn Prompt;
|
||||||
|
if is_perf_true {
|
||||||
/// Construct the transient prompt based on the normal nu_prompt
|
info!("update_prompt {}:{}:{}", file!(), line!(), column!());
|
||||||
pub(crate) fn make_transient_prompt(
|
}
|
||||||
config: &Config,
|
|
||||||
engine_state: &EngineState,
|
ret_val
|
||||||
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
@@ -1,552 +1,218 @@
|
|||||||
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_shape_color;
|
||||||
use nu_engine::env;
|
use nu_parser::{flatten_block, parse, FlatShape};
|
||||||
use nu_parser::{FlatShape, flatten_block, parse};
|
use nu_protocol::engine::{EngineState, StateWorkingSet};
|
||||||
use nu_protocol::{
|
use nu_protocol::Config;
|
||||||
Span,
|
|
||||||
ast::{Block, Expr, Expression, PipelineRedirection, RecordItem},
|
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
|
||||||
};
|
|
||||||
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 {
|
||||||
let result = highlight_syntax(&self.engine_state, &self.stack, line, cursor);
|
trace!("highlighting: {}", line);
|
||||||
result.text
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Result of a syntax highlight operation
|
let (shapes, global_span_offset) = {
|
||||||
#[derive(Default)]
|
let mut working_set = StateWorkingSet::new(&self.engine_state);
|
||||||
pub(crate) struct HighlightResult {
|
let (block, _) = parse(&mut working_set, None, line.as_bytes(), false, &[]);
|
||||||
/// The highlighted text
|
|
||||||
pub(crate) text: StyledText,
|
|
||||||
/// The span of any garbage that was highlighted
|
|
||||||
pub(crate) found_garbage: Option<Span>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn highlight_syntax(
|
let shapes = flatten_block(&working_set, &block);
|
||||||
engine_state: &EngineState,
|
(shapes, self.engine_state.next_span_start())
|
||||||
stack: &Stack,
|
};
|
||||||
line: &str,
|
|
||||||
cursor: usize,
|
|
||||||
) -> HighlightResult {
|
|
||||||
trace!("highlighting: {}", line);
|
|
||||||
|
|
||||||
let config = stack.get_config(engine_state);
|
let mut output = StyledText::default();
|
||||||
let highlight_resolved_externals = config.highlight_resolved_externals;
|
let mut last_seen_span = global_span_offset;
|
||||||
let mut working_set = StateWorkingSet::new(engine_state);
|
|
||||||
let block = parse(&mut working_set, None, line.as_bytes(), false);
|
|
||||||
let (shapes, global_span_offset) = {
|
|
||||||
let mut 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();
|
for shape in &shapes {
|
||||||
let paths = env::path_str(engine_state, stack, *span).ok();
|
if shape.0.end <= last_seen_span
|
||||||
let res = if let Ok(cwd) = engine_state.cwd(Some(stack)) {
|
|| last_seen_span < global_span_offset
|
||||||
which::which_in(str_word, paths.as_ref(), cwd).ok()
|
|| shape.0.start < global_span_offset
|
||||||
} else {
|
{
|
||||||
which::which_in_global(str_word, paths.as_ref())
|
// We've already output something for this span
|
||||||
.ok()
|
// so just skip this one
|
||||||
.and_then(|mut i| i.next())
|
continue;
|
||||||
};
|
|
||||||
if res.is_some() {
|
|
||||||
*shape = FlatShape::ExternalResolved;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
if shape.0.start > last_seen_span {
|
||||||
(shapes, engine_state.next_span_start())
|
let gap = line
|
||||||
};
|
[(last_seen_span - global_span_offset)..(shape.0.start - global_span_offset)]
|
||||||
|
.to_string();
|
||||||
let mut result = HighlightResult::default();
|
output.push((Style::new(), gap));
|
||||||
let mut last_seen_span = global_span_offset;
|
}
|
||||||
|
let next_token = line
|
||||||
let global_cursor_offset = cursor + global_span_offset;
|
[(shape.0.start - global_span_offset)..(shape.0.end - global_span_offset)]
|
||||||
let matching_brackets_pos = find_matching_brackets(
|
|
||||||
line,
|
|
||||||
&working_set,
|
|
||||||
&block,
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
);
|
|
||||||
|
|
||||||
for shape in &shapes {
|
|
||||||
if shape.0.end <= last_seen_span
|
|
||||||
|| last_seen_span < global_span_offset
|
|
||||||
|| shape.0.start < global_span_offset
|
|
||||||
{
|
|
||||||
// We've already output something for this span
|
|
||||||
// so just skip this one
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if shape.0.start > last_seen_span {
|
|
||||||
let gap = line
|
|
||||||
[(last_seen_span - global_span_offset)..(shape.0.start - global_span_offset)]
|
|
||||||
.to_string();
|
.to_string();
|
||||||
result.text.push((Style::new(), gap));
|
match shape.1 {
|
||||||
|
FlatShape::Garbage => output.push((
|
||||||
|
// nushell Garbage
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::Nothing => output.push((
|
||||||
|
// nushell Nothing
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::Binary => {
|
||||||
|
// nushell ?
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Bool => {
|
||||||
|
// nushell ?
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Int => {
|
||||||
|
// nushell Int
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Float => {
|
||||||
|
// nushell Decimal
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Range => output.push((
|
||||||
|
// nushell DotDot ?
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::InternalCall => output.push((
|
||||||
|
// nushell InternalCommand
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::External => {
|
||||||
|
// nushell ExternalCommand
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::ExternalArg => {
|
||||||
|
// nushell ExternalWord
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Literal => {
|
||||||
|
// nushell ?
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Operator => output.push((
|
||||||
|
// nushell Operator
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::Signature => output.push((
|
||||||
|
// nushell ?
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::String => {
|
||||||
|
// nushell String
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::StringInterpolation => {
|
||||||
|
// nushell ???
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::DateTime => {
|
||||||
|
// nushell ???
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::List => {
|
||||||
|
// nushell ???
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Table => {
|
||||||
|
// nushell ???
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Record => {
|
||||||
|
// nushell ???
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Block => {
|
||||||
|
// nushell ???
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Filepath => output.push((
|
||||||
|
// nushell Path
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::Directory => output.push((
|
||||||
|
// nushell Directory
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::GlobPattern => output.push((
|
||||||
|
// nushell GlobPattern
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::Variable => output.push((
|
||||||
|
// nushell Variable
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
FlatShape::Flag => {
|
||||||
|
// nushell Flag
|
||||||
|
output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
FlatShape::Custom(..) => output.push((
|
||||||
|
get_shape_color(shape.1.to_string(), &self.config),
|
||||||
|
next_token,
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
last_seen_span = shape.0.end;
|
||||||
}
|
}
|
||||||
let next_token = line
|
|
||||||
[(shape.0.start - global_span_offset)..(shape.0.end - global_span_offset)]
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let mut add_colored_token = |shape: &FlatShape, text: String| {
|
let remainder = line[(last_seen_span - global_span_offset)..].to_string();
|
||||||
result
|
if !remainder.is_empty() {
|
||||||
.text
|
output.push((Style::new(), remainder));
|
||||||
.push((get_shape_color(shape.as_str(), &config), text));
|
|
||||||
};
|
|
||||||
|
|
||||||
match shape.1 {
|
|
||||||
FlatShape::Garbage => {
|
|
||||||
result.found_garbage.get_or_insert_with(|| {
|
|
||||||
Span::new(
|
|
||||||
shape.0.start - global_span_offset,
|
|
||||||
shape.0.end - global_span_offset,
|
|
||||||
)
|
|
||||||
});
|
|
||||||
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(
|
|
||||||
line,
|
|
||||||
span,
|
|
||||||
&matching_brackets_pos,
|
|
||||||
global_span_offset,
|
|
||||||
);
|
|
||||||
for (part, highlight) in spans {
|
|
||||||
let start = part.start - span.start;
|
|
||||||
let end = part.end - span.start;
|
|
||||||
let text = next_token[start..end].to_string();
|
|
||||||
let mut style = get_shape_color(shape.as_str(), &config);
|
|
||||||
if highlight {
|
|
||||||
style = get_matching_brackets_style(style, &config);
|
|
||||||
}
|
|
||||||
result.text.push((style, text));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
FlatShape::Filepath => add_colored_token(&shape.1, next_token),
|
|
||||||
FlatShape::Directory => add_colored_token(&shape.1, 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::Redirection => add_colored_token(&shape.1, next_token),
|
|
||||||
FlatShape::Custom(..) => add_colored_token(&shape.1, next_token),
|
|
||||||
FlatShape::MatchPattern => add_colored_token(&shape.1, next_token),
|
|
||||||
}
|
}
|
||||||
last_seen_span = shape.0.end;
|
|
||||||
}
|
|
||||||
|
|
||||||
let remainder = line[(last_seen_span - global_span_offset)..].to_string();
|
output
|
||||||
if !remainder.is_empty() {
|
|
||||||
result.text.push((Style::new(), remainder));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
fn split_span_by_highlight_positions(
|
|
||||||
line: &str,
|
|
||||||
span: Span,
|
|
||||||
highlight_positions: &[usize],
|
|
||||||
global_span_offset: usize,
|
|
||||||
) -> Vec<(Span, bool)> {
|
|
||||||
let mut start = span.start;
|
|
||||||
let mut result: Vec<(Span, bool)> = Vec::new();
|
|
||||||
for pos in highlight_positions {
|
|
||||||
if start <= *pos && pos < &span.end {
|
|
||||||
if start < *pos {
|
|
||||||
result.push((Span::new(start, *pos), false));
|
|
||||||
}
|
|
||||||
let span_str = &line[pos - global_span_offset..span.end - global_span_offset];
|
|
||||||
let end = span_str
|
|
||||||
.chars()
|
|
||||||
.next()
|
|
||||||
.map(|c| pos + get_char_length(c))
|
|
||||||
.unwrap_or(pos + 1);
|
|
||||||
result.push((Span::new(*pos, end), true));
|
|
||||||
start = end;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if start < span.end {
|
|
||||||
result.push((Span::new(start, span.end), false));
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_matching_brackets(
|
|
||||||
line: &str,
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
block: &Block,
|
|
||||||
global_span_offset: usize,
|
|
||||||
global_cursor_offset: usize,
|
|
||||||
) -> Vec<usize> {
|
|
||||||
const BRACKETS: &str = "{}[]()";
|
|
||||||
|
|
||||||
// calculate first bracket position
|
|
||||||
let global_end_offset = line.len() + global_span_offset;
|
|
||||||
let global_bracket_pos =
|
|
||||||
if global_cursor_offset == global_end_offset && global_end_offset > global_span_offset {
|
|
||||||
// cursor is at the end of a non-empty string -- find block end at the previous position
|
|
||||||
if let Some(last_char) = line.chars().last() {
|
|
||||||
global_cursor_offset - get_char_length(last_char)
|
|
||||||
} else {
|
|
||||||
global_cursor_offset
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// cursor is in the middle of a string -- find block end at the current position
|
|
||||||
global_cursor_offset
|
|
||||||
};
|
|
||||||
|
|
||||||
// check that position contains bracket
|
|
||||||
let match_idx = global_bracket_pos - global_span_offset;
|
|
||||||
if match_idx >= line.len()
|
|
||||||
|| !BRACKETS.contains(get_char_at_index(line, match_idx).unwrap_or_default())
|
|
||||||
{
|
|
||||||
return Vec::new();
|
|
||||||
}
|
|
||||||
|
|
||||||
// find matching bracket by finding matching block end
|
|
||||||
let matching_block_end = find_matching_block_end_in_block(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
block,
|
|
||||||
global_span_offset,
|
|
||||||
global_bracket_pos,
|
|
||||||
);
|
|
||||||
if let Some(pos) = matching_block_end {
|
|
||||||
let matching_idx = pos - global_span_offset;
|
|
||||||
if BRACKETS.contains(get_char_at_index(line, matching_idx).unwrap_or_default()) {
|
|
||||||
return if global_bracket_pos < pos {
|
|
||||||
vec![global_bracket_pos, pos]
|
|
||||||
} else {
|
|
||||||
vec![pos, global_bracket_pos]
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Vec::new()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_matching_block_end_in_block(
|
|
||||||
line: &str,
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
block: &Block,
|
|
||||||
global_span_offset: usize,
|
|
||||||
global_cursor_offset: usize,
|
|
||||||
) -> Option<usize> {
|
|
||||||
for p in &block.pipelines {
|
|
||||||
for e in &p.elements {
|
|
||||||
if e.expr.span.contains(global_cursor_offset) {
|
|
||||||
if let Some(pos) = find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
&e.expr,
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
) {
|
|
||||||
return Some(pos);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_matching_block_end_in_expr(
|
|
||||||
line: &str,
|
|
||||||
working_set: &StateWorkingSet,
|
|
||||||
expression: &Expression,
|
|
||||||
global_span_offset: usize,
|
|
||||||
global_cursor_offset: usize,
|
|
||||||
) -> Option<usize> {
|
|
||||||
if expression.span.contains(global_cursor_offset) && expression.span.start >= global_span_offset
|
|
||||||
{
|
|
||||||
let expr_first = expression.span.start;
|
|
||||||
let span_str = &line
|
|
||||||
[expression.span.start - global_span_offset..expression.span.end - global_span_offset];
|
|
||||||
let expr_last = span_str
|
|
||||||
.chars()
|
|
||||||
.last()
|
|
||||||
.map(|c| expression.span.end - get_char_length(c))
|
|
||||||
.unwrap_or(expression.span.start);
|
|
||||||
|
|
||||||
return match &expression.expr {
|
|
||||||
// TODO: Can't these be handled with an `_ => None` branch? Refactor
|
|
||||||
Expr::Bool(_) => None,
|
|
||||||
Expr::Int(_) => None,
|
|
||||||
Expr::Float(_) => None,
|
|
||||||
Expr::Binary(_) => None,
|
|
||||||
Expr::Range(..) => None,
|
|
||||||
Expr::Var(_) => None,
|
|
||||||
Expr::VarDecl(_) => None,
|
|
||||||
Expr::ExternalCall(..) => None,
|
|
||||||
Expr::Operator(_) => None,
|
|
||||||
Expr::UnaryNot(_) => None,
|
|
||||||
Expr::Keyword(..) => None,
|
|
||||||
Expr::ValueWithUnit(..) => None,
|
|
||||||
Expr::DateTime(_) => None,
|
|
||||||
Expr::Filepath(_, _) => None,
|
|
||||||
Expr::Directory(_, _) => None,
|
|
||||||
Expr::GlobPattern(_, _) => None,
|
|
||||||
Expr::String(_) => None,
|
|
||||||
Expr::RawString(_) => None,
|
|
||||||
Expr::CellPath(_) => None,
|
|
||||||
Expr::ImportPattern(_) => None,
|
|
||||||
Expr::Overlay(_) => None,
|
|
||||||
Expr::Signature(_) => None,
|
|
||||||
Expr::MatchBlock(_) => None,
|
|
||||||
Expr::Nothing => None,
|
|
||||||
Expr::Garbage => None,
|
|
||||||
|
|
||||||
Expr::AttributeBlock(ab) => ab
|
|
||||||
.attributes
|
|
||||||
.iter()
|
|
||||||
.find_map(|attr| {
|
|
||||||
find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
&attr.expr,
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.or_else(|| {
|
|
||||||
find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
&ab.item,
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
|
|
||||||
Expr::Table(table) => {
|
|
||||||
if expr_last == global_cursor_offset {
|
|
||||||
// cursor is at table end
|
|
||||||
Some(expr_first)
|
|
||||||
} else if expr_first == global_cursor_offset {
|
|
||||||
// cursor is at table start
|
|
||||||
Some(expr_last)
|
|
||||||
} else {
|
|
||||||
// cursor is inside table
|
|
||||||
table
|
|
||||||
.columns
|
|
||||||
.iter()
|
|
||||||
.chain(table.rows.iter().flat_map(AsRef::as_ref))
|
|
||||||
.find_map(|expr| {
|
|
||||||
find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
expr,
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Expr::Record(exprs) => {
|
|
||||||
if expr_last == global_cursor_offset {
|
|
||||||
// cursor is at record end
|
|
||||||
Some(expr_first)
|
|
||||||
} else if expr_first == global_cursor_offset {
|
|
||||||
// cursor is at record start
|
|
||||||
Some(expr_last)
|
|
||||||
} else {
|
|
||||||
// cursor is inside record
|
|
||||||
exprs.iter().find_map(|expr| match expr {
|
|
||||||
RecordItem::Pair(k, v) => find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
k,
|
|
||||||
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| {
|
|
||||||
arg.expr().and_then(|expr| {
|
|
||||||
find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
expr,
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
|
|
||||||
Expr::FullCellPath(b) => find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
&b.head,
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
),
|
|
||||||
|
|
||||||
Expr::BinaryOp(lhs, op, rhs) => [lhs, op, rhs].into_iter().find_map(|expr| {
|
|
||||||
find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
expr,
|
|
||||||
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::Closure(block_id)
|
|
||||||
| Expr::RowCondition(block_id)
|
|
||||||
| Expr::Subexpression(block_id) => {
|
|
||||||
if expr_last == global_cursor_offset {
|
|
||||||
// cursor is at block end
|
|
||||||
Some(expr_first)
|
|
||||||
} else if expr_first == global_cursor_offset {
|
|
||||||
// cursor is at block start
|
|
||||||
Some(expr_last)
|
|
||||||
} else {
|
|
||||||
// cursor is inside block
|
|
||||||
let nested_block = working_set.get_block(*block_id);
|
|
||||||
find_matching_block_end_in_block(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
nested_block,
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Expr::StringInterpolation(exprs) | Expr::GlobInterpolation(exprs, _) => {
|
|
||||||
exprs.iter().find_map(|expr| {
|
|
||||||
find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
expr,
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
Expr::List(list) => {
|
|
||||||
if expr_last == global_cursor_offset {
|
|
||||||
// cursor is at list end
|
|
||||||
Some(expr_first)
|
|
||||||
} else if expr_first == global_cursor_offset {
|
|
||||||
// cursor is at list start
|
|
||||||
Some(expr_last)
|
|
||||||
} else {
|
|
||||||
list.iter().find_map(|item| {
|
|
||||||
find_matching_block_end_in_expr(
|
|
||||||
line,
|
|
||||||
working_set,
|
|
||||||
item.expr(),
|
|
||||||
global_span_offset,
|
|
||||||
global_cursor_offset,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_char_at_index(s: &str, index: usize) -> Option<char> {
|
|
||||||
s[index..].chars().next()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_char_length(c: char) -> usize {
|
|
||||||
c.to_string().len()
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,15 @@
|
|||||||
#![allow(clippy::byte_char_slices)]
|
use log::trace;
|
||||||
|
use nu_engine::eval_block;
|
||||||
use nu_cmd_base::hook::eval_hook;
|
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
|
||||||
use nu_engine::{eval_block, eval_block_with_early_return};
|
use nu_protocol::engine::StateWorkingSet;
|
||||||
use nu_parser::{Token, TokenContents, lex, parse, unescape_unquote_string};
|
use nu_protocol::CliError;
|
||||||
use nu_protocol::{
|
use nu_protocol::{
|
||||||
|
engine::{EngineState, Stack},
|
||||||
PipelineData, ShellError, Span, Value,
|
PipelineData, ShellError, Span, Value,
|
||||||
debugger::WithoutDebug,
|
|
||||||
engine::{EngineState, Stack, StateWorkingSet},
|
|
||||||
report_error::report_compile_error,
|
|
||||||
report_parse_error, report_parse_warning, report_shell_error,
|
|
||||||
};
|
};
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
use nu_utils::enable_vt_processing;
|
use nu_utils::enable_vt_processing;
|
||||||
use nu_utils::{escape_quote_string, 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.
|
||||||
//
|
//
|
||||||
@@ -43,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(),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,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(),
|
||||||
},
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,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);
|
||||||
@@ -106,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(
|
||||||
@@ -127,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.is_empty() {
|
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),
|
||||||
@@ -158,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(
|
||||||
@@ -171,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.is_empty() {
|
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),
|
||||||
@@ -186,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,
|
||||||
@@ -203,122 +197,132 @@ fn gather_env_vars(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Print a pipeline with formatting applied based on display_output hook.
|
|
||||||
///
|
|
||||||
/// This function should be preferred when printing values resulting from a completed evaluation.
|
|
||||||
/// For values printed as part of a command's execution, such as values printed by the `print` command,
|
|
||||||
/// the `PipelineData::print_table` function should be preferred instead as it is not config-dependent.
|
|
||||||
///
|
|
||||||
/// `no_newline` controls if we need to attach newline character to output.
|
|
||||||
pub fn print_pipeline(
|
|
||||||
engine_state: &mut EngineState,
|
|
||||||
stack: &mut Stack,
|
|
||||||
pipeline: PipelineData,
|
|
||||||
no_newline: bool,
|
|
||||||
) -> Result<(), ShellError> {
|
|
||||||
if let Some(hook) = engine_state.get_config().hooks.display_output.clone() {
|
|
||||||
let pipeline = eval_hook(
|
|
||||||
engine_state,
|
|
||||||
stack,
|
|
||||||
Some(pipeline),
|
|
||||||
vec![],
|
|
||||||
&hook,
|
|
||||||
"display_output",
|
|
||||||
)?;
|
|
||||||
pipeline.print_raw(engine_state, no_newline, false)
|
|
||||||
} else {
|
|
||||||
// if display_output isn't set, we should still prefer to print with some formatting
|
|
||||||
pipeline.print_table(engine_state, stack, no_newline, false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn eval_source(
|
pub fn eval_source(
|
||||||
engine_state: &mut EngineState,
|
engine_state: &mut EngineState,
|
||||||
stack: &mut Stack,
|
stack: &mut Stack,
|
||||||
source: &[u8],
|
source: &[u8],
|
||||||
fname: &str,
|
fname: &str,
|
||||||
input: PipelineData,
|
input: PipelineData,
|
||||||
allow_return: bool,
|
) -> bool {
|
||||||
) -> i32 {
|
trace!("eval_source");
|
||||||
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
|
|
||||||
.get(engine_state)
|
|
||||||
);
|
|
||||||
|
|
||||||
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);
|
|
||||||
return Ok(true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
(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(mut pipeline_data) => {
|
||||||
} else {
|
if let PipelineData::ExternalStream { exit_code, .. } = &mut pipeline_data {
|
||||||
eval_block::<WithoutDebug>(engine_state, stack, &block, input)
|
if let Some(exit_code) = exit_code.take().and_then(|it| it.last()) {
|
||||||
}?;
|
stack.add_env_var("LAST_EXIT_CODE".to_string(), exit_code);
|
||||||
|
} else {
|
||||||
|
set_last_exit_code(stack, 0);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
set_last_exit_code(stack, 0);
|
||||||
|
}
|
||||||
|
|
||||||
let no_newline = matches!(&pipeline, &PipelineData::ByteStream(..));
|
if let Err(err) = pipeline_data.print(engine_state, stack, false, false) {
|
||||||
print_pipeline(engine_state, stack, pipeline, no_newline)?;
|
let working_set = StateWorkingSet::new(engine_state);
|
||||||
|
|
||||||
Ok(false)
|
report_error(&working_set, &err);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)]
|
||||||
@@ -343,10 +347,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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,17 @@
|
|||||||
use nu_parser::parse;
|
use nu_parser::{parse, ParseError};
|
||||||
use nu_protocol::{
|
use nu_protocol::engine::{EngineState, StateWorkingSet};
|
||||||
ParseError,
|
|
||||||
engine::{EngineState, StateWorkingSet},
|
|
||||||
};
|
|
||||||
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
|
||||||
|
|||||||
65
crates/nu-cli/tests/alias.rs
Normal file
65
crates/nu-cli/tests/alias.rs
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
pub mod support;
|
||||||
|
|
||||||
|
use nu_cli::NuCompleter;
|
||||||
|
use reedline::Completer;
|
||||||
|
use support::{match_suggestions, new_engine};
|
||||||
|
|
||||||
|
#[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)
|
||||||
|
}
|
||||||
@@ -1,296 +0,0 @@
|
|||||||
use nu_protocol::HistoryFileFormat;
|
|
||||||
use nu_test_support::{Outcome, nu};
|
|
||||||
use reedline::{
|
|
||||||
FileBackedHistory, History, HistoryItem, HistoryItemId, ReedlineError, SearchQuery,
|
|
||||||
SqliteBackedHistory,
|
|
||||||
};
|
|
||||||
use rstest::rstest;
|
|
||||||
use tempfile::TempDir;
|
|
||||||
|
|
||||||
struct Test {
|
|
||||||
cfg_dir: TempDir,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Test {
|
|
||||||
fn new(history_format: &'static str) -> Self {
|
|
||||||
let cfg_dir = tempfile::Builder::new()
|
|
||||||
.prefix("history_import_test")
|
|
||||||
.tempdir()
|
|
||||||
.unwrap();
|
|
||||||
// Assigning to $env.config.history.file_format seems to work only in startup
|
|
||||||
// configuration.
|
|
||||||
std::fs::write(
|
|
||||||
cfg_dir.path().join("env.nu"),
|
|
||||||
format!("$env.config.history.file_format = {history_format:?}"),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
Self { cfg_dir }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn nu(&self, cmd: impl AsRef<str>) -> Outcome {
|
|
||||||
let env = [(
|
|
||||||
"XDG_CONFIG_HOME".to_string(),
|
|
||||||
self.cfg_dir.path().to_str().unwrap().to_string(),
|
|
||||||
)];
|
|
||||||
let env_config = self.cfg_dir.path().join("env.nu");
|
|
||||||
nu!(envs: env, env_config: env_config, cmd.as_ref())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open_plaintext(&self) -> Result<FileBackedHistory, ReedlineError> {
|
|
||||||
FileBackedHistory::with_file(
|
|
||||||
100,
|
|
||||||
self.cfg_dir
|
|
||||||
.path()
|
|
||||||
.join("nushell")
|
|
||||||
.join(HistoryFileFormat::Plaintext.default_file_name()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open_sqlite(&self) -> Result<SqliteBackedHistory, ReedlineError> {
|
|
||||||
SqliteBackedHistory::with_file(
|
|
||||||
self.cfg_dir
|
|
||||||
.path()
|
|
||||||
.join("nushell")
|
|
||||||
.join(HistoryFileFormat::Sqlite.default_file_name()),
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open_backend(&self, format: HistoryFileFormat) -> Result<Box<dyn History>, ReedlineError> {
|
|
||||||
fn boxed(be: impl History + 'static) -> Box<dyn History> {
|
|
||||||
Box::new(be)
|
|
||||||
}
|
|
||||||
use HistoryFileFormat::*;
|
|
||||||
match format {
|
|
||||||
Plaintext => self.open_plaintext().map(boxed),
|
|
||||||
Sqlite => self.open_sqlite().map(boxed),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enum HistorySource {
|
|
||||||
Vec(Vec<HistoryItem>),
|
|
||||||
Command(&'static str),
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TestCase {
|
|
||||||
dst_format: HistoryFileFormat,
|
|
||||||
dst_history: Vec<HistoryItem>,
|
|
||||||
src_history: HistorySource,
|
|
||||||
want_history: Vec<HistoryItem>,
|
|
||||||
}
|
|
||||||
|
|
||||||
const EMPTY_TEST_CASE: TestCase = TestCase {
|
|
||||||
dst_format: HistoryFileFormat::Plaintext,
|
|
||||||
dst_history: Vec::new(),
|
|
||||||
src_history: HistorySource::Vec(Vec::new()),
|
|
||||||
want_history: Vec::new(),
|
|
||||||
};
|
|
||||||
|
|
||||||
impl TestCase {
|
|
||||||
fn run(self) {
|
|
||||||
use HistoryFileFormat::*;
|
|
||||||
let test = Test::new(match self.dst_format {
|
|
||||||
Plaintext => "plaintext",
|
|
||||||
Sqlite => "sqlite",
|
|
||||||
});
|
|
||||||
save_all(
|
|
||||||
&mut *test.open_backend(self.dst_format).unwrap(),
|
|
||||||
self.dst_history,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let outcome = match self.src_history {
|
|
||||||
HistorySource::Vec(src_history) => {
|
|
||||||
let src_format = match self.dst_format {
|
|
||||||
Plaintext => Sqlite,
|
|
||||||
Sqlite => Plaintext,
|
|
||||||
};
|
|
||||||
save_all(&mut *test.open_backend(src_format).unwrap(), src_history).unwrap();
|
|
||||||
test.nu("history import")
|
|
||||||
}
|
|
||||||
HistorySource::Command(cmd) => {
|
|
||||||
let mut cmd = cmd.to_string();
|
|
||||||
cmd.push_str(" | history import");
|
|
||||||
test.nu(cmd)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
assert!(outcome.status.success());
|
|
||||||
let got = query_all(&*test.open_backend(self.dst_format).unwrap()).unwrap();
|
|
||||||
|
|
||||||
// Compare just the commands first, for readability.
|
|
||||||
fn commands_only(items: &[HistoryItem]) -> Vec<&str> {
|
|
||||||
items
|
|
||||||
.iter()
|
|
||||||
.map(|item| item.command_line.as_str())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
assert_eq!(commands_only(&got), commands_only(&self.want_history));
|
|
||||||
// If commands match, compare full items.
|
|
||||||
assert_eq!(got, self.want_history);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn query_all(history: &dyn History) -> Result<Vec<HistoryItem>, ReedlineError> {
|
|
||||||
history.search(SearchQuery::everything(
|
|
||||||
reedline::SearchDirection::Forward,
|
|
||||||
None,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn save_all(history: &mut dyn History, items: Vec<HistoryItem>) -> Result<(), ReedlineError> {
|
|
||||||
for item in items {
|
|
||||||
history.save(item)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
const EMPTY_ITEM: HistoryItem = HistoryItem {
|
|
||||||
command_line: String::new(),
|
|
||||||
id: None,
|
|
||||||
start_timestamp: None,
|
|
||||||
session_id: None,
|
|
||||||
hostname: None,
|
|
||||||
cwd: None,
|
|
||||||
duration: None,
|
|
||||||
exit_status: None,
|
|
||||||
more_info: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn history_import_pipe_string() {
|
|
||||||
TestCase {
|
|
||||||
dst_format: HistoryFileFormat::Plaintext,
|
|
||||||
src_history: HistorySource::Command("echo bar"),
|
|
||||||
want_history: vec![HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(0)),
|
|
||||||
command_line: "bar".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
}],
|
|
||||||
..EMPTY_TEST_CASE
|
|
||||||
}
|
|
||||||
.run();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn history_import_pipe_record() {
|
|
||||||
TestCase {
|
|
||||||
dst_format: HistoryFileFormat::Sqlite,
|
|
||||||
src_history: HistorySource::Command("[[cwd command]; [/tmp some_command]]"),
|
|
||||||
want_history: vec![HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(1)),
|
|
||||||
command_line: "some_command".to_string(),
|
|
||||||
cwd: Some("/tmp".to_string()),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
}],
|
|
||||||
..EMPTY_TEST_CASE
|
|
||||||
}
|
|
||||||
.run();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn to_empty_plaintext() {
|
|
||||||
TestCase {
|
|
||||||
dst_format: HistoryFileFormat::Plaintext,
|
|
||||||
src_history: HistorySource::Vec(vec![
|
|
||||||
HistoryItem {
|
|
||||||
command_line: "foo".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
HistoryItem {
|
|
||||||
command_line: "bar".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
want_history: vec![
|
|
||||||
HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(0)),
|
|
||||||
command_line: "foo".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(1)),
|
|
||||||
command_line: "bar".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
],
|
|
||||||
..EMPTY_TEST_CASE
|
|
||||||
}
|
|
||||||
.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn to_empty_sqlite() {
|
|
||||||
TestCase {
|
|
||||||
dst_format: HistoryFileFormat::Sqlite,
|
|
||||||
src_history: HistorySource::Vec(vec![
|
|
||||||
HistoryItem {
|
|
||||||
command_line: "foo".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
HistoryItem {
|
|
||||||
command_line: "bar".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
want_history: vec![
|
|
||||||
HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(1)),
|
|
||||||
command_line: "foo".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(2)),
|
|
||||||
command_line: "bar".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
],
|
|
||||||
..EMPTY_TEST_CASE
|
|
||||||
}
|
|
||||||
.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[rstest]
|
|
||||||
#[case::plaintext(HistoryFileFormat::Plaintext)]
|
|
||||||
#[case::sqlite(HistoryFileFormat::Sqlite)]
|
|
||||||
fn to_existing(#[case] dst_format: HistoryFileFormat) {
|
|
||||||
TestCase {
|
|
||||||
dst_format,
|
|
||||||
dst_history: vec![
|
|
||||||
HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(0)),
|
|
||||||
command_line: "original-1".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(1)),
|
|
||||||
command_line: "original-2".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
],
|
|
||||||
src_history: HistorySource::Vec(vec![HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(1)),
|
|
||||||
command_line: "new".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
}]),
|
|
||||||
want_history: vec![
|
|
||||||
HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(0)),
|
|
||||||
command_line: "original-1".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(1)),
|
|
||||||
command_line: "original-2".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
HistoryItem {
|
|
||||||
id: Some(HistoryItemId::new(2)),
|
|
||||||
command_line: "new".to_string(),
|
|
||||||
..EMPTY_ITEM
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
.run()
|
|
||||||
}
|
|
||||||
@@ -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");
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
mod history_import;
|
|
||||||
mod keybindings_list;
|
|
||||||
mod nu_highlight;
|
|
||||||
@@ -1,13 +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");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nu_highlight_where_row_condition() {
|
|
||||||
let actual = nu!("'ls | where a b 12345(' | nu-highlight | ansi strip");
|
|
||||||
assert_eq!(actual.out, "ls | where a b 12345(");
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user