Compare commits

..

1 Commits

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

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

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

# User-Facing Changes

_(List of all changes that impact the user experience here. This helps
us keep track of breaking changes.)_

# Tests + Formatting

Don't forget to add tests that cover your changes.

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass

# After Submitting

If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
2022-12-06 06:17:06 +13:00
690 changed files with 13384 additions and 27209 deletions

View File

@ -11,26 +11,9 @@ jobs:
strategy:
fail-fast: true
matrix:
# Pinning to Ubuntu 20.04 because building on newer Ubuntu versions causes linux-gnu
# builds to link against a too-new-for-many-Linux-installs glibc version. Consider
# revisiting this when 20.04 is closer to EOL (April 2025)
platform: [windows-latest, macos-latest, ubuntu-20.04]
style: [default, dataframe]
platform: [windows-latest, macos-latest, ubuntu-latest]
rust:
- stable
include:
- style: default
flags: ""
- style: dataframe
flags: "--features=dataframe "
exclude:
# only test dataframes on Ubuntu (the fastest platform)
- platform: windows-latest
style: dataframe
- platform: macos-latest
style: dataframe
runs-on: ${{ matrix.platform }}
env:
@ -42,11 +25,17 @@ jobs:
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
- name: cargo fmt
run: cargo fmt --all -- --check
- name: Rustfmt
uses: actions-rs/cargo@v1.0.1
with:
command: fmt
args: --all -- --check
- name: Clippy
run: cargo clippy --workspace ${{ matrix.flags }}--exclude nu_plugin_* -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
uses: actions-rs/cargo@v1.0.1
with:
command: clippy
args: --workspace --exclude nu_plugin_* -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
nu-tests:
env:
@ -55,7 +44,7 @@ jobs:
strategy:
fail-fast: true
matrix:
platform: [windows-latest, macos-latest, ubuntu-20.04]
platform: [windows-latest, macos-latest, ubuntu-latest]
style: [default, dataframe]
rust:
- stable
@ -80,7 +69,10 @@ jobs:
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
- name: Tests
run: cargo test --workspace --profile ci --exclude nu_plugin_* ${{ matrix.flags }}
uses: actions-rs/cargo@v1.0.1
with:
command: test
args: --workspace --profile ci --exclude nu_plugin_* ${{ matrix.flags }}
python-virtualenv:
env:
@ -89,7 +81,7 @@ jobs:
strategy:
fail-fast: true
matrix:
platform: [ubuntu-20.04, macos-latest, windows-latest]
platform: [ubuntu-latest, macos-latest, windows-latest]
rust:
- stable
py:
@ -104,7 +96,10 @@ jobs:
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
- name: Install Nushell
run: cargo install --locked --path=. --profile ci --no-default-features
uses: actions-rs/cargo@v1.0.1
with:
command: install
args: --locked --path=. --profile ci --no-default-features
- name: Setup Python
uses: actions/setup-python@v4
@ -113,9 +108,8 @@ jobs:
- run: python -m pip install tox
# Get only the latest tagged version for stability reasons
- name: Install virtualenv
run: git clone https://github.com/pypa/virtualenv.git && cd virtualenv && git checkout $(git describe --tags | cut -d - -f 1)
run: git clone https://github.com/pypa/virtualenv.git
shell: bash
- name: Test Nushell in virtualenv
@ -131,7 +125,7 @@ jobs:
strategy:
fail-fast: true
matrix:
platform: [windows-latest, macos-latest, ubuntu-20.04]
platform: [windows-latest, macos-latest, ubuntu-latest]
rust:
- stable
@ -144,7 +138,13 @@ jobs:
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
- name: Clippy
run: cargo clippy --package nu_plugin_* ${{ matrix.flags }} -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
uses: actions-rs/cargo@v1.0.1
with:
command: clippy
args: --package nu_plugin_* ${{ matrix.flags }} -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
- name: Tests
run: cargo test --profile ci --package nu_plugin_*
uses: actions-rs/cargo@v1.0.1
with:
command: test
args: --profile ci --package nu_plugin_*

View File

@ -6,21 +6,6 @@
# REF:
# 1. https://github.com/volks73/cargo-wix
# Added 2022-11-29 when Windows packaging wouldn't work
# because softprops/action-gh-release was broken
# To run this manual for windows
# let-env TARGET = 'x86_64-pc-windows-msvc'
# let-env TARGET_RUSTFLAGS = ''
# let-env GITHUB_WORKSPACE = 'C:\Users\dschroeder\source\repos\forks\nushell'
# Pass 1 let-env _EXTRA_ = 'bin'
# Pass 2 let-env _EXTRA_ = 'msi'
# make sure 7z.exe is in your path https://www.7-zip.org/download.html
# make sure aria2c.exe is in your path https://github.com/aria2/aria2
# make sure you have the wixtools installed https://wixtoolset.org/
# set os below like this because it's what github's runner is named
# let os = 'windows-latest'
# The main binary file to be released
let bin = 'nu'
let os = $env.OS
@ -48,7 +33,6 @@ $'Start building ($bin)...'; hr-line
# ----------------------------------------------------------------------------
if $os in [$USE_UBUNTU, 'macos-latest'] {
if $os == $USE_UBUNTU {
sudo apt update
sudo apt-get install libxcb-composite0-dev -y
}
if $target == 'aarch64-unknown-linux-gnu' {
@ -59,10 +43,6 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
sudo apt-get install pkg-config gcc-arm-linux-gnueabihf -y
let-env CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc'
cargo-build-nu $flags
} else if $target == 'riscv64gc-unknown-linux-gnu' {
sudo apt-get install gcc-riscv64-linux-gnu -y
let-env CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER = 'riscv64-linux-gnu-gcc'
cargo-build-nu $flags
} else {
# musl-tools to fix 'Failed to find tool. Is `musl-gcc` installed?'
# Actually just for x86_64-unknown-linux-musl target

View File

@ -27,7 +27,6 @@ jobs:
- x86_64-unknown-linux-musl
- aarch64-unknown-linux-gnu
- armv7-unknown-linux-gnueabihf
- riscv64gc-unknown-linux-gnu
extra: ['bin']
include:
- target: aarch64-apple-darwin
@ -56,26 +55,24 @@ jobs:
- target: armv7-unknown-linux-gnueabihf
os: ubuntu-20.04
target_rustflags: ''
- target: riscv64gc-unknown-linux-gnu
os: ubuntu-20.04
target_rustflags: ''
runs-on: ${{matrix.os}}
steps:
- uses: actions/checkout@v3.1.0
- name: Update Rust Toolchain Target
run: |
echo "targets = ['${{matrix.target}}']" >> rust-toolchain.toml
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
- name: Install Rust Toolchain Components
uses: actions-rs/toolchain@v1.0.6
with:
override: true
profile: minimal
toolchain: stable
target: ${{ matrix.target }}
- name: Setup Nushell
uses: hustcer/setup-nu@v3
with:
version: 0.72.1
version: 0.71.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

416
Cargo.lock generated
View File

@ -80,12 +80,6 @@ dependencies = [
"libc",
]
[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "ansi-str"
version = "0.5.0"
@ -95,30 +89,21 @@ dependencies = [
"ansitok",
]
[[package]]
name = "ansi-str"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b1ed1c166829a0ccb5d79caa0f75cb4abd4adb2ce2c096755b7ad5ffdb0990"
dependencies = [
"ansitok",
]
[[package]]
name = "ansitok"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "220044e6a1bb31ddee4e3db724d29767f352de47445a6cd75e1a173142136c83"
dependencies = [
"nom",
"nom 7.1.1",
"vte",
]
[[package]]
name = "anyhow"
version = "1.0.66"
version = "1.0.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "216261ddc8289130e551ddcd5ce8a064710c0d064a4d2895c67151c92b5443f6"
checksum = "98161a4e3e2184da77bb14f02184cdd111e83bbbcc9979dfee3c44b9a85f5602"
[[package]]
name = "array-init-cursor"
@ -445,25 +430,19 @@ checksum = "6c58ec36aac5066d5ca17df51b3e70279f5670a72102f5752cb7e7c856adfc70"
[[package]]
name = "calamine"
version = "0.19.1"
version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6381d1037ee9b8a6c8eb97936add0331a1aabd148d5b6f35f1cda6e5dec44f40"
checksum = "b86ca78da4bdce5ac0f0bdbc0218ad14232f1e668376e044233f64c527cf5abb"
dependencies = [
"byteorder",
"codepage",
"encoding_rs",
"log",
"quick-xml",
"quick-xml 0.19.0",
"serde",
"zip",
]
[[package]]
name = "cassowary"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
[[package]]
name = "cast"
version = "0.3.0"
@ -485,7 +464,7 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom",
"nom 7.1.1",
]
[[package]]
@ -548,33 +527,6 @@ dependencies = [
"phf_codegen 0.11.1",
]
[[package]]
name = "ciborium"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c137568cc60b904a7724001b35ce2630fd00d5d84805fbb608ab89509d788f"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346de753af073cc87b52b2083a506b38ac176a44cfb05497b622e27be899b369"
[[package]]
name = "ciborium-ll"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "213030a2b5a4e0c0892b6652260cf6ccac84827b83a85a534e178e3906c4cf1b"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "clang-sys"
version = "1.4.0"
@ -588,23 +540,13 @@ dependencies = [
[[package]]
name = "clap"
version = "3.2.23"
version = "2.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71655c45cb9845d3270c9d6df84ebe72b4dad3c2ba3f7023ad47c144e4e473a5"
checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
dependencies = [
"bitflags",
"clap_lex",
"indexmap",
"textwrap 0.16.0",
]
[[package]]
name = "clap_lex"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"
dependencies = [
"os_str_bytes",
"textwrap 0.11.0",
"unicode-width",
]
[[package]]
@ -716,16 +658,15 @@ dependencies = [
[[package]]
name = "criterion"
version = "0.4.0"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c76e09c1aae2bc52b3d2f29e13c6572553b30c4aa1b8a49fd70de6412654cb"
checksum = "b01d6de93b2b6c65e17c634a26653a29d107b3c98c607c765bf38d041531cd8f"
dependencies = [
"anes",
"atty",
"cast",
"ciborium",
"clap",
"criterion-plot",
"csv",
"itertools",
"lazy_static",
"num-traits",
@ -734,6 +675,7 @@ dependencies = [
"rayon",
"regex",
"serde",
"serde_cbor",
"serde_derive",
"serde_json",
"tinytemplate",
@ -742,9 +684,9 @@ dependencies = [
[[package]]
name = "criterion-plot"
version = "0.5.0"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
checksum = "2673cc8207403546f45f5fd319a974b1e6983ad1a3ee7e6041650013be041876"
dependencies = [
"cast",
"itertools",
@ -1210,7 +1152,7 @@ checksum = "e11dcc7e4d79a8c89b9ab4c6f5c30b1fc4a83c420792da3542fd31179ed5f517"
dependencies = [
"cfg-if 1.0.0",
"rustix",
"windows-sys 0.36.1",
"windows-sys",
]
[[package]]
@ -1231,7 +1173,7 @@ dependencies = [
"cfg-if 1.0.0",
"libc",
"redox_syscall",
"windows-sys 0.36.1",
"windows-sys",
]
[[package]]
@ -1314,6 +1256,12 @@ dependencies = [
"libc",
]
[[package]]
name = "fuchsia-cprng"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba"
[[package]]
name = "fuchsia-zircon"
version = "0.3.3"
@ -1932,9 +1880,9 @@ dependencies = [
[[package]]
name = "json_to_table"
version = "0.3.1"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0be33515faeb3773f550c80fd7a889148164e58f7e3cf36467718c8ce71ee55"
checksum = "408f09e42613f7a9902ecf2f30bcd053cf9f5668d0b1493ae1669070338d661b"
dependencies = [
"serde_json",
"tabled",
@ -2153,15 +2101,6 @@ dependencies = [
"cfg-if 1.0.0",
]
[[package]]
name = "lru"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6e8aaa3f231bb4bd57b84b2d5dc3ae7f350265df8aa96492e0bc394a1571909"
dependencies = [
"hashbrown",
]
[[package]]
name = "lscolors"
version = "0.12.0"
@ -2268,6 +2207,16 @@ dependencies = [
"autocfg",
]
[[package]]
name = "meval"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f79496a5651c8d57cd033c5add8ca7ee4e3d5f7587a4777484640d9cb60392d9"
dependencies = [
"fnv",
"nom 1.2.4",
]
[[package]]
name = "miette"
version = "5.3.0"
@ -2304,16 +2253,6 @@ version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
[[package]]
name = "mime_guess"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@ -2357,7 +2296,7 @@ dependencies = [
"libc",
"log",
"wasi 0.11.0+wasi-snapshot-preview1",
"windows-sys 0.36.1",
"windows-sys",
]
[[package]]
@ -2472,6 +2411,12 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
[[package]]
name = "nom"
version = "1.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5b8c256fd9471521bcb84c3cdba98921497f1a331cbc15b8030fc63b82050ce"
[[package]]
name = "nom"
version = "7.1.1"
@ -2492,7 +2437,7 @@ dependencies = [
"indent_write",
"joinery",
"memchr",
"nom",
"nom 7.1.1",
]
[[package]]
@ -2524,12 +2469,11 @@ dependencies = [
[[package]]
name = "nu"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"assert_cmd",
"atty",
"chrono",
"criterion",
"crossterm 0.24.0",
"ctrlc",
"hamcrest2",
@ -2579,7 +2523,7 @@ dependencies = [
[[package]]
name = "nu-cli"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"atty",
"chrono",
@ -2587,6 +2531,7 @@ dependencies = [
"fancy-regex",
"fuzzy-matcher",
"is_executable",
"lazy_static",
"log",
"miette",
"nu-ansi-term",
@ -2598,7 +2543,6 @@ dependencies = [
"nu-protocol",
"nu-test-support",
"nu-utils",
"once_cell",
"percent-encoding",
"reedline",
"rstest",
@ -2608,25 +2552,21 @@ dependencies = [
[[package]]
name = "nu-color-config"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"nu-ansi-term",
"nu-engine",
"nu-json",
"nu-protocol",
"nu-test-support",
"nu-utils",
"nu-table",
"serde",
"tabled",
]
[[package]]
name = "nu-command"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"Inflector",
"alphanumeric-sort",
"atty",
"base64",
"byteorder",
"bytesize",
@ -2652,17 +2592,17 @@ dependencies = [
"indexmap",
"is-root",
"itertools",
"lazy_static",
"libc",
"log",
"lscolors",
"md-5",
"meval",
"mime",
"mime_guess",
"notify",
"nu-ansi-term",
"nu-color-config",
"nu-engine",
"nu-explore",
"nu-glob",
"nu-json",
"nu-parser",
@ -2678,19 +2618,16 @@ dependencies = [
"num-format",
"num-traits",
"once_cell",
"open",
"pathdiff",
"percent-encoding",
"polars",
"powierza-coefficient",
"proptest",
"quick-xml",
"quick-xml 0.23.1",
"quickcheck",
"quickcheck_macros",
"rand 0.8.5",
"rayon",
"reedline",
"regex",
"reqwest",
"roxmltree",
"rstest",
@ -2723,7 +2660,7 @@ dependencies = [
[[package]]
name = "nu-engine"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"chrono",
"nu-glob",
@ -2733,45 +2670,30 @@ dependencies = [
"sysinfo",
]
[[package]]
name = "nu-explore"
version = "0.74.0"
dependencies = [
"ansi-str 0.7.2",
"crossterm 0.24.0",
"lscolors",
"nu-ansi-term",
"nu-color-config",
"nu-engine",
"nu-json",
"nu-parser",
"nu-protocol",
"nu-table",
"nu-utils",
"strip-ansi-escapes",
"terminal_size 0.2.1",
"tui",
]
[[package]]
name = "nu-glob"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"doc-comment",
"tempdir",
]
[[package]]
name = "nu-json"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"fancy-regex",
"lazy_static",
"linked-hash-map",
"nu-path",
"num-traits",
"serde",
"serde_json",
]
[[package]]
name = "nu-parser"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"bytesize",
"chrono",
@ -2788,7 +2710,7 @@ dependencies = [
[[package]]
name = "nu-path"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"dirs-next",
"omnipath",
@ -2797,9 +2719,10 @@ dependencies = [
[[package]]
name = "nu-plugin"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"bincode",
"criterion",
"nu-engine",
"nu-protocol",
"rmp",
@ -2810,7 +2733,7 @@ dependencies = [
[[package]]
name = "nu-pretty-hex"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"heapless",
"nu-ansi-term",
@ -2819,17 +2742,15 @@ dependencies = [
[[package]]
name = "nu-protocol"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"byte-unit",
"chrono",
"chrono-humanize",
"fancy-regex",
"indexmap",
"lru",
"miette",
"nu-json",
"nu-test-support",
"nu-utils",
"num-format",
"serde",
@ -2843,7 +2764,7 @@ dependencies = [
[[package]]
name = "nu-system"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"atty",
"chrono",
@ -2861,15 +2782,12 @@ dependencies = [
[[package]]
name = "nu-table"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"atty",
"json_to_table",
"nu-ansi-term",
"nu-color-config",
"nu-engine",
"nu-protocol",
"nu-test-support",
"nu-utils",
"serde_json",
"tabled",
@ -2877,7 +2795,7 @@ dependencies = [
[[package]]
name = "nu-term-grid"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"nu-utils",
"unicode-width",
@ -2885,21 +2803,21 @@ dependencies = [
[[package]]
name = "nu-test-support"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"getset",
"hamcrest2",
"lazy_static",
"nu-glob",
"nu-path",
"nu-utils",
"num-format",
"once_cell",
"tempfile",
]
[[package]]
name = "nu-utils"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"crossterm_winapi",
"lscolors",
@ -2920,7 +2838,7 @@ dependencies = [
[[package]]
name = "nu_plugin_example"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"nu-plugin",
"nu-protocol",
@ -2928,7 +2846,7 @@ dependencies = [
[[package]]
name = "nu_plugin_gstat"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"git2",
"nu-engine",
@ -2938,7 +2856,7 @@ dependencies = [
[[package]]
name = "nu_plugin_inc"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"nu-plugin",
"nu-protocol",
@ -2947,7 +2865,7 @@ dependencies = [
[[package]]
name = "nu_plugin_query"
version = "0.74.0"
version = "0.72.1"
dependencies = [
"gjson",
"nu-engine",
@ -3138,16 +3056,6 @@ version = "11.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
[[package]]
name = "open"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2078c0039e6a54a0c42c28faa984e115fb4c2d5bf2208f77d1961002df8576f8"
dependencies = [
"pathdiff",
"windows-sys 0.42.0",
]
[[package]]
name = "openssl"
version = "0.10.42"
@ -3203,12 +3111,6 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "os_str_bytes"
version = "6.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee"
[[package]]
name = "output_vt100"
version = "0.1.3"
@ -3236,7 +3138,7 @@ version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1526bb6aa9f10ec339fb10360f22c57edf81d5678d0278e93bc12a47ffbe4b01"
dependencies = [
"ansi-str 0.5.0",
"ansi-str",
"ansitok",
"bytecount",
"fnv",
@ -3263,7 +3165,7 @@ dependencies = [
"libc",
"redox_syscall",
"smallvec",
"windows-sys 0.36.1",
"windows-sys",
]
[[package]]
@ -3705,14 +3607,14 @@ version = "0.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a63d338dec139f56dacc692ca63ad35a6be6a797442479b55acd611d79e906"
dependencies = [
"nom",
"nom 7.1.1",
]
[[package]]
name = "powierza-coefficient"
version = "1.0.2"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04123079750026568dff0e68efe1ca676f6686023f3bf7686b87dab661c0375b"
checksum = "64e2c03bca73af2a7a2c021a6b3b4991658b760b2e0a84e3e425a9c9eda2ba7f"
[[package]]
name = "ppv-lite86"
@ -3869,14 +3771,23 @@ checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quick-xml"
version = "0.25.0"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58e21a144a0ffb5fad7b464babcdab934a325ad69b7c0373bcfef5cbd9799ca9"
checksum = "b3d72d5477478f85bd00b6521780dfba1ec6cdaadcf90b8b181c36d7de561f9b"
dependencies = [
"encoding_rs",
"memchr",
]
[[package]]
name = "quick-xml"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11bafc859c6815fbaffbbbf4229ecb767ac913fecb27f9ad4343662e9ef099ea"
dependencies = [
"memchr",
]
[[package]]
name = "quickcheck"
version = "1.0.3"
@ -3908,6 +3819,19 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293"
dependencies = [
"fuchsia-cprng",
"libc",
"rand_core 0.3.1",
"rdrand",
"winapi 0.3.9",
]
[[package]]
name = "rand"
version = "0.7.3"
@ -3953,6 +3877,21 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "rand_core"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b"
dependencies = [
"rand_core 0.4.2",
]
[[package]]
name = "rand_core"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc"
[[package]]
name = "rand_core"
version = "0.5.1"
@ -4032,6 +3971,15 @@ dependencies = [
"num_cpus",
]
[[package]]
name = "rdrand"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2"
dependencies = [
"rand_core 0.3.1",
]
[[package]]
name = "redox_syscall"
version = "0.2.16"
@ -4194,9 +4142,9 @@ dependencies = [
[[package]]
name = "roxmltree"
version = "0.16.0"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb6d47b59770b0ae88c7f270c68502832ec14d8c7ab5f7a584f204bb76dbfd8e"
checksum = "921904a62e410e37e215c40381b7117f830d9d89ba60ab5236170541dd25646b"
dependencies = [
"xmlparser",
]
@ -4317,7 +4265,7 @@ dependencies = [
"io-lifetimes",
"libc",
"linux-raw-sys",
"windows-sys 0.36.1",
"windows-sys",
]
[[package]]
@ -4360,7 +4308,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88d6731146462ea25d9244b2ed5fd1d716d25c52e4d54aa4fb0f3c4e9854dbe2"
dependencies = [
"lazy_static",
"windows-sys 0.36.1",
"windows-sys",
]
[[package]]
@ -4481,6 +4429,16 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde_cbor"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5"
dependencies = [
"half",
"serde",
]
[[package]]
name = "serde_derive"
version = "1.0.145"
@ -4919,7 +4877,7 @@ version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56c3ee73732ffceaea7b8f6b719ce3bb17f253fa27461ffeaf568ebd0cdb4b85"
dependencies = [
"ansi-str 0.5.0",
"ansi-str",
"papergrid",
"tabled_derive",
"unicode-width",
@ -4938,6 +4896,16 @@ dependencies = [
"syn",
]
[[package]]
name = "tempdir"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8"
dependencies = [
"rand 0.4.6",
"remove_dir_all",
]
[[package]]
name = "tempfile"
version = "3.3.0"
@ -4989,7 +4957,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8440c860cf79def6164e4a0a983bcc2305d82419177a0e0c71930d049e3ac5a1"
dependencies = [
"rustix",
"windows-sys 0.36.1",
"windows-sys",
]
[[package]]
@ -4998,6 +4966,15 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "507e9898683b6c43a9aa55b64259b721b52ba226e0f3779137e50ad114a4c90b"
[[package]]
name = "textwrap"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
dependencies = [
"unicode-width",
]
[[package]]
name = "textwrap"
version = "0.15.1"
@ -5009,12 +4986,6 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "textwrap"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d"
[[package]]
name = "thin-slice"
version = "0.1.1"
@ -5117,9 +5088,9 @@ dependencies = [
[[package]]
name = "tokio"
version = "1.24.1"
version = "1.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d9f76183f91ecfb55e1d7d5602bd1d979e38a3a522fe900241cf195624d67ae"
checksum = "a9e03c497dc955702ba729190dc4aac6f2a0ce97f913e5b1b5912fc5039d9099"
dependencies = [
"autocfg",
"bytes",
@ -5129,7 +5100,7 @@ dependencies = [
"num_cpus",
"pin-project-lite",
"socket2",
"windows-sys 0.42.0",
"winapi 0.3.9",
]
[[package]]
@ -5213,19 +5184,6 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
[[package]]
name = "tui"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccdd26cbd674007e649a272da4475fb666d3aa0ad0531da7136db6fab0e5bad1"
dependencies = [
"bitflags",
"cassowary",
"crossterm 0.25.0",
"unicode-segmentation",
"unicode-width",
]
[[package]]
name = "typed-arena"
version = "1.7.0"
@ -5283,15 +5241,6 @@ dependencies = [
"version_check",
]
[[package]]
name = "unicase"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
dependencies = [
"version_check",
]
[[package]]
name = "unicode-bidi"
version = "0.3.8"
@ -5594,7 +5543,7 @@ dependencies = [
"bstr",
"const_format",
"itertools",
"nom",
"nom 7.1.1",
"nom-supreme",
"pori",
"regex",
@ -5695,21 +5644,6 @@ dependencies = [
"windows_x86_64_msvc 0.36.1",
]
[[package]]
name = "windows-sys"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc 0.42.0",
"windows_i686_gnu 0.42.0",
"windows_i686_msvc 0.42.0",
"windows_x86_64_gnu 0.42.0",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc 0.42.0",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.0"
@ -5812,9 +5746,9 @@ dependencies = [
[[package]]
name = "xmlparser"
version = "0.13.5"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d25c75bf9ea12c4040a97f829154768bbbce366287e2dc044af160cd79a13fd"
checksum = "114ba2b24d2167ef6d67d7d04c8cc86522b87f490025f39f0303b7db5bf5e3d8"
[[package]]
name = "yansi"
@ -5824,14 +5758,14 @@ checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec"
[[package]]
name = "zip"
version = "0.6.3"
version = "0.5.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "537ce7411d25e54e8ae21a7ce0b15840e7bfcff15b51d697ec3266cc76bdf080"
checksum = "93ab48844d61251bb3835145c521d88aa4031d7139e8485990f60ca911fa0815"
dependencies = [
"byteorder",
"crc32fast",
"crossbeam-utils",
"flate2",
"thiserror",
]
[[package]]

View File

@ -3,14 +3,14 @@ authors = ["The Nushell Project Developers"]
default-run = "nu"
description = "A new type of shell"
documentation = "https://www.nushell.sh/book/"
edition = "2021"
edition = "2018"
exclude = ["images"]
homepage = "https://www.nushell.sh"
license = "MIT"
name = "nu"
repository = "https://github.com/nushell/nushell"
rust-version = "1.60"
version = "0.74.0"
version = "0.72.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -45,20 +45,20 @@ ctrlc = "3.2.1"
log = "0.4"
miette = { version = "5.1.0", features = ["fancy-no-backtrace"] }
nu-ansi-term = "0.46.0"
nu-cli = { path="./crates/nu-cli", version = "0.74.0" }
nu-color-config = { path = "./crates/nu-color-config", version = "0.74.0" }
nu-command = { path="./crates/nu-command", version = "0.74.0" }
nu-engine = { path="./crates/nu-engine", version = "0.74.0" }
nu-json = { path="./crates/nu-json", version = "0.74.0" }
nu-parser = { path="./crates/nu-parser", version = "0.74.0" }
nu-path = { path="./crates/nu-path", version = "0.74.0" }
nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.74.0" }
nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.74.0" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.74.0" }
nu-system = { path = "./crates/nu-system", version = "0.74.0" }
nu-table = { path = "./crates/nu-table", version = "0.74.0" }
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.74.0" }
nu-utils = { path = "./crates/nu-utils", version = "0.74.0" }
nu-cli = { path="./crates/nu-cli", version = "0.72.1" }
nu-color-config = { path = "./crates/nu-color-config", version = "0.72.1" }
nu-command = { path="./crates/nu-command", version = "0.72.1" }
nu-engine = { path="./crates/nu-engine", version = "0.72.1" }
nu-json = { path="./crates/nu-json", version = "0.72.1" }
nu-parser = { path="./crates/nu-parser", version = "0.72.1" }
nu-path = { path="./crates/nu-path", version = "0.72.1" }
nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.72.1" }
nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.72.1" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.72.1" }
nu-system = { path = "./crates/nu-system", version = "0.72.1" }
nu-table = { path = "./crates/nu-table", version = "0.72.1" }
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.72.1" }
nu-utils = { path = "./crates/nu-utils", version = "0.72.1" }
reedline = { version = "0.14.0", features = ["bashisms", "sqlite"]}
rayon = "1.5.1"
@ -80,10 +80,9 @@ nix = { version = "0.25", default-features = false, features = ["signal", "proce
atty = "0.2"
[dev-dependencies]
nu-test-support = { path="./crates/nu-test-support", version = "0.74.0" }
nu-test-support = { path="./crates/nu-test-support", version = "0.72.1" }
tempfile = "3.2.0"
assert_cmd = "2.0.2"
criterion = "0.4"
pretty_assertions = "1.0.0"
serial_test = "0.8.0"
hamcrest2 = "0.3.0"
@ -141,18 +140,3 @@ path = "src/main.rs"
# changing versions in each sub-crate of the workspace is tedious
[patch.crates-io]
# reedline = { git = "https://github.com/nushell/reedline.git", branch = "main" }
# Criterion benchmarking setup
# Run all benchmarks with `cargo bench`
# Run individual benchmarks like `cargo bench -- <regex>` e.g. `cargo bench -- parse`
[[bench]]
name = "encoder_benchmark"
harness = false
[[bench]]
name = "eval_benchmark"
harness = false
[[bench]]
name = "parser_benchmark"
harness = false

View File

@ -1,9 +0,0 @@
# Configuration for cross-rs: https://github.com/cross-rs/cross
# Run cross-rs like this:
# cross build --target aarch64-unknown-linux-musl --release
[target.aarch64-unknown-linux-gnu]
dockerfile = "./docker/cross-rs/aarch64-unknown-linux-gnu.dockerfile"
[target.aarch64-unknown-linux-musl]
dockerfile = "./docker/cross-rs/aarch64-unknown-linux-musl.dockerfile"

View File

@ -1,6 +1,6 @@
# Nushell <!-- omit in toc -->
[![Crates.io](https://img.shields.io/crates/v/nu.svg)](https://crates.io/crates/nu)
![Build Status](https://img.shields.io/github/actions/workflow/status/nushell/nushell/ci.yml?branch=main)
![Build Status](https://img.shields.io/github/workflow/status/nushell/nushell/continuous-integration)
[![Discord](https://img.shields.io/discord/601130461678272522.svg?logo=discord)](https://discord.gg/NtAbbGn)
[![The Changelog #363](https://img.shields.io/badge/The%20Changelog-%23363-61c192.svg)](https://changelog.com/podcast/363)
[![@nu_shell](https://img.shields.io/badge/twitter-@nu_shell-1DA1F3?style=flat-square)](https://twitter.com/nu_shell)
@ -47,7 +47,7 @@ brew 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:
@ -174,8 +174,6 @@ 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 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.
## 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.

View File

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

View File

@ -1,42 +0,0 @@
use criterion::{criterion_group, criterion_main, Criterion};
use nu_cli::eval_source;
use nu_protocol::{PipelineData, Span, Value};
use nu_utils::{get_default_config, get_default_env};
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("eval default_env.nu", |b| {
b.iter(|| {
let mut engine_state = nu_command::create_default_context();
let mut stack = nu_protocol::engine::Stack::new();
eval_source(
&mut engine_state,
&mut stack,
get_default_env().as_bytes(),
"default_env.nu",
PipelineData::empty(),
)
})
});
c.bench_function("eval default_config.nu", |b| {
b.iter(|| {
let mut engine_state = nu_command::create_default_context();
// parsing config.nu breaks without PWD set
engine_state.add_env_var(
"PWD".into(),
Value::string("/some/dir".to_string(), Span::test_data()),
);
let mut stack = nu_protocol::engine::Stack::new();
eval_source(
&mut engine_state,
&mut stack,
get_default_config().as_bytes(),
"default_config.nu",
PipelineData::empty(),
)
})
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

View File

@ -1,34 +0,0 @@
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use nu_parser::parse;
use nu_protocol::{Span, Value};
use nu_utils::{get_default_config, get_default_env};
fn criterion_benchmark(c: &mut Criterion) {
let mut engine_state = nu_command::create_default_context();
// parsing config.nu breaks without PWD set
engine_state.add_env_var(
"PWD".into(),
Value::string("/some/dir".to_string(), Span::test_data()),
);
let default_env = get_default_env().as_bytes();
c.bench_function("parse_default_env_file", |b| {
b.iter_batched(
|| nu_protocol::engine::StateWorkingSet::new(&engine_state),
|mut working_set| parse(&mut working_set, None, default_env, false, &[]),
BatchSize::SmallInput,
)
});
let default_config = get_default_config().as_bytes();
c.bench_function("parse_default_config_file", |b| {
b.iter_batched(
|| nu_protocol::engine::StateWorkingSet::new(&engine_state),
|mut working_set| parse(&mut working_set, None, default_config, false, &[]),
BatchSize::SmallInput,
)
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

View File

@ -5,7 +5,7 @@
@echo.
echo Building nushell.exe
cargo build --features=dataframe
cargo build cargo build --features=dataframe
@echo.
@cd crates\nu_plugin_example

View File

@ -5,21 +5,21 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cli"
edition = "2021"
license = "MIT"
name = "nu-cli"
version = "0.74.0"
version = "0.72.1"
[dev-dependencies]
nu-test-support = { path="../nu-test-support", version = "0.74.0" }
nu-command = { path = "../nu-command", version = "0.74.0" }
nu-test-support = { path="../nu-test-support", version = "0.72.1" }
nu-command = { path = "../nu-command", version = "0.72.1" }
rstest = {version = "0.15.0", default-features = false}
[dependencies]
nu-engine = { path = "../nu-engine", version = "0.74.0" }
nu-path = { path = "../nu-path", version = "0.74.0" }
nu-parser = { path = "../nu-parser", version = "0.74.0" }
nu-protocol = { path = "../nu-protocol", version = "0.74.0" }
nu-utils = { path = "../nu-utils", version = "0.74.0" }
nu-engine = { path = "../nu-engine", version = "0.72.1" }
nu-path = { path = "../nu-path", version = "0.72.1" }
nu-parser = { path = "../nu-parser", version = "0.72.1" }
nu-protocol = { path = "../nu-protocol", version = "0.72.1" }
nu-utils = { path = "../nu-utils", version = "0.72.1" }
nu-ansi-term = "0.46.0"
nu-color-config = { path = "../nu-color-config", version = "0.74.0" }
nu-color-config = { path = "../nu-color-config", version = "0.72.1" }
reedline = { version = "0.14.0", features = ["bashisms", "sqlite"]}
atty = "0.2.14"
@ -28,7 +28,7 @@ crossterm = "0.24.0"
fancy-regex = "0.10.0"
fuzzy-matcher = "0.3.7"
is_executable = "1.0.1"
once_cell = "1.16.0"
lazy_static = "1.4.0"
log = "0.4"
miette = { version = "5.1.0", features = ["fancy-no-backtrace"] }
percent-encoding = "2"

View File

@ -94,7 +94,10 @@ impl CommandCompletion {
value: String::from_utf8_lossy(&x.0).to_string(),
description: x.1,
extra: None,
span: reedline::Span::new(span.start - offset, span.end - offset),
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
});
@ -105,7 +108,10 @@ impl CommandCompletion {
value: String::from_utf8_lossy(&x).to_string(),
description: None,
extra: None,
span: reedline::Span::new(span.start - offset, span.end - offset),
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
});
@ -122,15 +128,15 @@ impl CommandCompletion {
value: x,
description: None,
extra: None,
span: reedline::Span::new(span.start - offset, span.end - offset),
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
});
let results_strings: Vec<String> =
results.clone().into_iter().map(|x| x.value).collect();
for external in results_external {
if results_strings.contains(&external.value) {
if results.contains(&external) {
results.push(Suggestion {
value: format!("^{}", external.value),
description: None,
@ -181,7 +187,10 @@ impl Completer for CommandCompletion {
let subcommands = if let Some(last) = last {
self.complete_commands(
working_set,
Span::new(last.0.start, pos),
Span {
start: last.0.start,
end: pos,
},
offset,
false,
options.match_algorithm,

View File

@ -77,7 +77,10 @@ impl NuCompleter {
Value::List {
vals: spans
.iter()
.map(|it| Value::string(it, Span::unknown()))
.map(|it| Value::String {
val: it.to_string(),
span: Span::unknown(),
})
.collect(),
span: Span::unknown(),
},
@ -89,7 +92,7 @@ impl NuCompleter {
&self.engine_state,
&mut callee_stack,
block,
PipelineData::empty(),
PipelineData::new(span),
true,
true,
);
@ -98,8 +101,14 @@ impl NuCompleter {
Ok(pd) => {
let value = pd.into_value(span);
if let Value::List { vals, span: _ } = value {
let result =
map_value_completions(vals.iter(), Span::new(span.start, span.end), offset);
let result = map_value_completions(
vals.iter(),
Span {
start: span.start,
end: span.end,
},
offset,
);
return Some(result);
}
@ -156,12 +165,15 @@ impl NuCompleter {
// Create a new span
let new_span = if flat_idx == 0 {
Span::new(flat.0.start, flat.0.end - 1 - span_offset)
Span {
start: flat.0.start,
end: flat.0.end - 1 - span_offset,
}
} else {
Span::new(
flat.0.start - span_offset,
flat.0.end - 1 - span_offset,
)
Span {
start: flat.0.start - span_offset,
end: flat.0.end - 1 - span_offset,
}
};
// Parses the prefix. Completion should look up to the cursor position, not after.

View File

@ -52,13 +52,13 @@ impl Completer for CustomCompletion {
head: span,
arguments: vec![
Argument::Positional(Expression {
span: Span::unknown(),
span: Span { start: 0, end: 0 },
ty: Type::String,
expr: Expr::String(self.line.clone()),
custom_completion: None,
}),
Argument::Positional(Expression {
span: Span::unknown(),
span: Span { start: 0, end: 0 },
ty: Type::Int,
expr: Expr::Int(line_pos as i64),
custom_completion: None,
@ -66,9 +66,8 @@ impl Completer for CustomCompletion {
],
redirect_stdout: true,
redirect_stderr: true,
parser_info: vec![],
},
PipelineData::empty(),
PipelineData::new(span),
);
let mut custom_completion_options = None;

View File

@ -136,12 +136,8 @@ pub fn directory_completion(
file_name.push(SEP);
}
// Fix files or folders with quotes or hash
if path.contains('\'')
|| path.contains('"')
|| path.contains(' ')
|| path.contains('#')
{
// Fix files or folders with quotes
if path.contains('\'') || path.contains('"') || path.contains(' ') {
path = format!("`{}`", path);
}

View File

@ -141,14 +141,8 @@ pub fn file_path_completion(
file_name.push(SEP);
}
// Fix files or folders with quotes or hashes
if path.contains('\'')
|| path.contains('"')
|| path.contains(' ')
|| path.contains('#')
|| path.contains('(')
|| path.contains(')')
{
// Fix files or folders with quotes
if path.contains('\'') || path.contains('"') || path.contains(' ') {
path = format!("`{}`", path);
}

View File

@ -9,8 +9,6 @@ use reedline::Suggestion;
use std::str;
use std::sync::Arc;
use super::MatchAlgorithm;
#[derive(Clone)]
pub struct VariableCompletion {
engine_state: Arc<EngineState>, // TODO: Is engine state necessary? It's already a part of working set in fetch()
@ -75,11 +73,10 @@ impl Completer for VariableCompletion {
for suggestion in
nested_suggestions(val.clone(), nested_levels, current_span)
{
if options.match_algorithm.matches_u8_insensitive(
options.case_sensitive,
suggestion.value.as_bytes(),
&prefix,
) {
if options
.match_algorithm
.matches_u8(suggestion.value.as_bytes(), &prefix)
{
output.push(suggestion);
}
}
@ -89,11 +86,10 @@ impl Completer for VariableCompletion {
} else {
// No nesting provided, return all env vars
for env_var in env_vars {
if options.match_algorithm.matches_u8_insensitive(
options.case_sensitive,
env_var.0.as_bytes(),
&prefix,
) {
if options
.match_algorithm
.matches_u8(env_var.0.as_bytes(), &prefix)
{
output.push(Suggestion {
value: env_var.0,
description: None,
@ -115,16 +111,18 @@ impl Completer for VariableCompletion {
&self.engine_state,
&self.stack,
nu_protocol::NU_VARIABLE_ID,
nu_protocol::Span::new(current_span.start, current_span.end),
nu_protocol::Span {
start: current_span.start,
end: current_span.end,
},
) {
for suggestion in
nested_suggestions(nuval, self.var_context.1.clone(), current_span)
{
if options.match_algorithm.matches_u8_insensitive(
options.case_sensitive,
suggestion.value.as_bytes(),
&prefix,
) {
if options
.match_algorithm
.matches_u8(suggestion.value.as_bytes(), &prefix)
{
output.push(suggestion);
}
}
@ -136,18 +134,23 @@ impl Completer for VariableCompletion {
// 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::new(span.start, span.end));
let var = self.stack.get_var(
var_id,
Span {
start: span.start,
end: span.end,
},
);
// If the value exists and it's of type Record
if let Ok(value) = var {
for suggestion in
nested_suggestions(value, self.var_context.1.clone(), current_span)
{
if options.match_algorithm.matches_u8_insensitive(
options.case_sensitive,
suggestion.value.as_bytes(),
&prefix,
) {
if options
.match_algorithm
.matches_u8(suggestion.value.as_bytes(), &prefix)
{
output.push(suggestion);
}
}
@ -159,11 +162,10 @@ impl Completer for VariableCompletion {
// Variable completion (e.g: $en<tab> to complete $env)
for builtin in builtins {
if options.match_algorithm.matches_u8_insensitive(
options.case_sensitive,
builtin.as_bytes(),
&prefix,
) {
if options
.match_algorithm
.matches_u8(builtin.as_bytes(), &prefix)
{
output.push(Suggestion {
value: builtin.to_string(),
description: None,
@ -185,11 +187,7 @@ impl Completer for VariableCompletion {
.rev()
{
for v in &overlay_frame.vars {
if options.match_algorithm.matches_u8_insensitive(
options.case_sensitive,
v.0,
&prefix,
) {
if options.match_algorithm.matches_u8(v.0, &prefix) {
output.push(Suggestion {
value: String::from_utf8_lossy(v.0).to_string(),
description: None,
@ -211,11 +209,7 @@ impl Completer for VariableCompletion {
.rev()
{
for v in &overlay_frame.vars {
if options.match_algorithm.matches_u8_insensitive(
options.case_sensitive,
v.0,
&prefix,
) {
if options.match_algorithm.matches_u8(v.0, &prefix) {
output.push(Suggestion {
value: String::from_utf8_lossy(v.0).to_string(),
description: None,
@ -287,7 +281,7 @@ fn recursive_value(val: Value, sublevels: Vec<Vec<u8>>) -> Value {
// Current sublevel value not found
return Value::Nothing {
span: Span::unknown(),
span: Span { start: 0, end: 0 },
};
}
_ => return val,
@ -296,13 +290,3 @@ fn recursive_value(val: Value, sublevels: Vec<Vec<u8>>) -> Value {
val
}
impl MatchAlgorithm {
pub fn matches_u8_insensitive(&self, sensitive: bool, haystack: &[u8], needle: &[u8]) -> bool {
if sensitive {
self.matches_u8(haystack, needle)
} else {
self.matches_u8(&haystack.to_ascii_lowercase(), &needle.to_ascii_lowercase())
}
}
}

View File

@ -8,7 +8,7 @@ use nu_path::canonicalize_with;
use nu_protocol::engine::{EngineState, Stack, StateWorkingSet};
#[cfg(feature = "plugin")]
use nu_protocol::Spanned;
use nu_protocol::{HistoryFileFormat, PipelineData};
use nu_protocol::{HistoryFileFormat, PipelineData, Span};
use std::path::PathBuf;
#[cfg(feature = "plugin")]
@ -38,7 +38,7 @@ pub fn read_plugin_file(
stack,
&contents,
&plugin_filename,
PipelineData::empty(),
PipelineData::new(Span::new(0, 0)),
);
}
}
@ -85,7 +85,7 @@ pub fn eval_config_contents(
stack,
&contents,
&config_filename,
PipelineData::empty(),
PipelineData::new(Span::new(0, 0)),
);
// Merge the environment in case env vars changed in the config

View File

@ -2,13 +2,13 @@ use crate::util::{eval_source, report_error};
use log::info;
use log::trace;
use miette::{IntoDiagnostic, Result};
use nu_engine::{convert_env_values, current_dir};
use nu_engine::convert_env_values;
use nu_parser::parse;
use nu_path::canonicalize_with;
use nu_protocol::Type;
use nu_protocol::{
ast::Call,
engine::{EngineState, Stack, StateWorkingSet},
Config, PipelineData, ShellError, Span, Type, Value,
Config, PipelineData, Span, Value,
};
use nu_utils::stdout_write_all_and_flush;
@ -27,75 +27,14 @@ pub fn evaluate_file(
std::process::exit(1);
}
let cwd = current_dir(engine_state, stack)?;
let file = std::fs::read(&path).into_diagnostic()?;
let file_path = {
match canonicalize_with(&path, &cwd) {
Ok(p) => p,
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(
&working_set,
&ShellError::FileNotFoundCustom(
format!("Could not access file '{}': {:?}", path, e.to_string()),
Span::unknown(),
),
);
std::process::exit(1);
}
}
};
let file_path_str = match file_path.to_str() {
Some(s) => s,
None => {
let working_set = StateWorkingSet::new(engine_state);
report_error(
&working_set,
&ShellError::NonUtf8Custom(
format!(
"Input file name '{}' is not valid UTF8",
file_path.to_string_lossy()
),
Span::unknown(),
),
);
std::process::exit(1);
}
};
let file = match std::fs::read(&file_path).into_diagnostic() {
Ok(p) => p,
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(
&working_set,
&ShellError::FileNotFoundCustom(
format!(
"Could not read file '{}': {:?}",
file_path_str,
e.to_string()
),
Span::unknown(),
),
);
std::process::exit(1);
}
};
engine_state.start_in_file(Some(file_path_str));
let mut parent = file_path.clone();
parent.pop();
stack.add_env_var(
"FILE_PWD".to_string(),
Value::string(parent.to_string_lossy(), Span::unknown()),
);
engine_state.start_in_file(Some(&path));
let mut working_set = StateWorkingSet::new(engine_state);
trace!("parsing file: {}", file_path_str);
let _ = parse(&mut working_set, Some(file_path_str), &file, false, &[]);
trace!("parsing file: {}", path);
let _ = parse(&mut working_set, Some(&path), &file, false, &[]);
if working_set.find_decl(b"main", &Type::Any).is_some() {
let args = format!("main {}", args.join(" "));
@ -104,15 +43,15 @@ pub fn evaluate_file(
engine_state,
stack,
&file,
file_path_str,
PipelineData::empty(),
&path,
PipelineData::new(Span::new(0, 0)),
) {
std::process::exit(1);
}
if !eval_source(engine_state, stack, args.as_bytes(), "<commandline>", input) {
std::process::exit(1);
}
} else if !eval_source(engine_state, stack, &file, file_path_str, input) {
} else if !eval_source(engine_state, stack, &file, &path, input) {
std::process::exit(1);
}

View File

@ -42,14 +42,20 @@ impl Completer for NuMenuCompleter {
if let Some(buffer) = block.signature.get_positional(0) {
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);
}
}
if let Some(position) = block.signature.get_positional(1) {
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);
}
}

View File

@ -1,6 +1,6 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Type, Value};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Value};
use reedline::Highlighter;
#[derive(Clone)]
@ -12,9 +12,7 @@ impl Command for NuHighlight {
}
fn signature(&self) -> Signature {
Signature::build("nu-highlight")
.category(Category::Strings)
.input_output_types(vec![(Type::String, Type::String)])
Signature::build("nu-highlight").category(Category::Strings)
}
fn usage(&self) -> &str {

View File

@ -2,8 +2,7 @@ use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Type,
Value,
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Value,
};
#[derive(Clone)]
@ -16,7 +15,6 @@ impl Command for Print {
fn signature(&self) -> Signature {
Signature::build("print")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.rest("rest", SyntaxShape::Any, "the values to print")
.switch(
"no-newline",
@ -52,13 +50,14 @@ Since this command has no output, there is no point in piping it with other comm
let args: Vec<Value> = call.rest(engine_state, stack, 0)?;
let no_newline = call.has_flag("no-newline");
let to_stderr = call.has_flag("stderr");
let head = call.head;
for arg in args {
arg.into_pipeline_data()
.print(engine_state, stack, no_newline, to_stderr)?;
}
Ok(PipelineData::empty())
Ok(PipelineData::new(head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,10 +1,10 @@
use crate::util::report_error;
use crate::NushellPrompt;
use log::trace;
use log::info;
use nu_engine::eval_subexpression;
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
Config, PipelineData, Value,
Config, PipelineData, Span, Value,
};
use reedline::Prompt;
@ -37,9 +37,13 @@ fn get_prompt_string(
let block = engine_state.get_block(block_id);
let mut stack = stack.captures_to_stack(&captures);
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
let ret_val =
eval_subexpression(engine_state, &mut stack, block, PipelineData::empty());
trace!(
let ret_val = eval_subexpression(
engine_state,
&mut stack,
block,
PipelineData::new(Span::new(0, 0)), // Don't try this at home, 0 span is ignored
);
info!(
"get_prompt_string (block) {}:{}:{}",
file!(),
line!(),
@ -58,8 +62,13 @@ fn get_prompt_string(
Value::Block { val: block_id, .. } => {
let block = engine_state.get_block(block_id);
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
let ret_val = eval_subexpression(engine_state, stack, block, PipelineData::empty());
trace!(
let ret_val = eval_subexpression(
engine_state,
stack,
block,
PipelineData::new(Span::new(0, 0)), // Don't try this at home, 0 span is ignored
);
info!(
"get_prompt_string (block) {}:{}:{}",
file!(),
line!(),
@ -148,7 +157,7 @@ pub(crate) fn update_prompt<'prompt>(
);
let ret_val = nu_prompt as &dyn Prompt;
trace!("update_prompt {}:{}:{}", file!(), line!(), column!());
info!("update_prompt {}:{}:{}", file!(), line!(), column!());
ret_val
}

View File

@ -1,13 +1,14 @@
use super::DescriptionMenu;
use crate::{menus::NuMenuCompleter, NuHelpCompleter};
use crossterm::event::{KeyCode, KeyModifiers};
use nu_color_config::{color_record_to_nustyle, lookup_ansi_color_style};
use nu_color_config::lookup_ansi_color_style;
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
create_menus,
color_value_string, create_menus,
engine::{EngineState, Stack, StateWorkingSet},
extract_value, Config, ParsedKeybinding, ParsedMenu, PipelineData, ShellError, Span, Value,
extract_value, Config, IntoPipelineData, ParsedKeybinding, ParsedMenu, PipelineData,
ShellError, Span, Value,
};
use reedline::{
default_emacs_keybindings, default_vi_insert_keybindings, default_vi_normal_keybindings,
@ -109,7 +110,7 @@ pub(crate) fn add_menus(
};
let mut temp_stack = Stack::new();
let input = PipelineData::Empty;
let input = Value::nothing(Span::test_data()).into_pipeline_data();
let res = eval_block(&engine_state, &mut temp_stack, &block, input, false, false)?;
if let PipelineData::Value(value, None) = res {
@ -158,11 +159,14 @@ macro_rules! add_style {
($name:expr, $cols: expr, $vals:expr, $span:expr, $config: expr, $menu:expr, $f:expr) => {
$menu = match extract_value($name, $cols, $vals, $span) {
Ok(text) => {
let style = match text {
Value::String { val, .. } => lookup_ansi_color_style(&val),
Value::Record { .. } => color_record_to_nustyle(&text),
_ => lookup_ansi_color_style("green"),
let text = match text {
Value::String { val, .. } => val.clone(),
Value::Record { cols, vals, span } => {
color_value_string(span, cols, vals, $config).into_string("", $config)
}
_ => "green".to_string(),
};
let style = lookup_ansi_color_style(&text);
$f($menu, style)
}
Err(_) => $menu,
@ -679,9 +683,9 @@ fn add_parsed_keybinding(
let fn_num: u8 = c[1..]
.parse()
.ok()
.filter(|num| matches!(num, 1..=20))
.filter(|num| matches!(num, 1..=12))
.ok_or(ShellError::UnsupportedConfigValue(
"(f1|f2|...|f20)".to_string(),
"(f1|f2|...|f12)".to_string(),
format!("unknown function key: {}", c),
keybinding.keycode.span()?,
))?;
@ -989,7 +993,10 @@ mod test {
#[test]
fn test_send_event() {
let cols = vec!["send".to_string()];
let vals = vec![Value::test_string("Enter")];
let vals = vec![Value::String {
val: "Enter".to_string(),
span: Span::test_data(),
}];
let span = Span::test_data();
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap();
@ -1009,7 +1016,10 @@ mod test {
#[test]
fn test_edit_event() {
let cols = vec!["edit".to_string()];
let vals = vec![Value::test_string("Clear")];
let vals = vec![Value::String {
val: "Clear".to_string(),
span: Span::test_data(),
}];
let span = Span::test_data();
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap();
@ -1033,8 +1043,14 @@ mod test {
fn test_send_menu() {
let cols = vec!["send".to_string(), "name".to_string()];
let vals = vec![
Value::test_string("Menu"),
Value::test_string("history_menu"),
Value::String {
val: "Menu".to_string(),
span: Span::test_data(),
},
Value::String {
val: "history_menu".to_string(),
span: Span::test_data(),
},
];
let span = Span::test_data();
@ -1060,8 +1076,14 @@ mod test {
// Menu event
let cols = vec!["send".to_string(), "name".to_string()];
let vals = vec![
Value::test_string("Menu"),
Value::test_string("history_menu"),
Value::String {
val: "Menu".to_string(),
span: Span::test_data(),
},
Value::String {
val: "history_menu".to_string(),
span: Span::test_data(),
},
];
let menu_event = Value::Record {
@ -1072,7 +1094,10 @@ mod test {
// Enter event
let cols = vec!["send".to_string()];
let vals = vec![Value::test_string("Enter")];
let vals = vec![Value::String {
val: "Enter".to_string(),
span: Span::test_data(),
}];
let enter_event = Value::Record {
cols,
@ -1113,8 +1138,14 @@ mod test {
// Menu event
let cols = vec!["send".to_string(), "name".to_string()];
let vals = vec![
Value::test_string("Menu"),
Value::test_string("history_menu"),
Value::String {
val: "Menu".to_string(),
span: Span::test_data(),
},
Value::String {
val: "history_menu".to_string(),
span: Span::test_data(),
},
];
let menu_event = Value::Record {
@ -1125,7 +1156,10 @@ mod test {
// Enter event
let cols = vec!["send".to_string()];
let vals = vec![Value::test_string("Enter")];
let vals = vec![Value::String {
val: "Enter".to_string(),
span: Span::test_data(),
}];
let enter_event = Value::Record {
cols,
@ -1153,7 +1187,10 @@ mod test {
#[test]
fn test_error() {
let cols = vec!["not_exist".to_string()];
let vals = vec![Value::test_string("Enter")];
let vals = vec![Value::String {
val: "Enter".to_string(),
span: Span::test_data(),
}];
let span = Span::test_data();
let b = EventType::try_from_columns(&cols, &vals, &span);

View File

@ -5,9 +5,11 @@ use crate::{
util::{eval_source, get_guaranteed_cwd, report_error, report_error_new},
NuHighlighter, NuValidator, NushellPrompt,
};
use fancy_regex::Regex;
use lazy_static::lazy_static;
use log::{info, trace, warn};
use miette::{IntoDiagnostic, Result};
use nu_color_config::StyleComputer;
use nu_color_config::get_color_config;
use nu_engine::{convert_env_values, eval_block, eval_block_with_early_return};
use nu_parser::{lex, parse, trim_quotes_str};
use nu_protocol::{
@ -72,10 +74,19 @@ pub fn evaluate_repl(
// seed env vars
stack.add_env_var(
"CMD_DURATION_MS".into(),
Value::string("0823", Span::unknown()),
Value::String {
val: "0823".to_string(),
span: Span { start: 0, end: 0 },
},
);
stack.add_env_var("LAST_EXIT_CODE".into(), Value::int(0, Span::unknown()));
stack.add_env_var(
"LAST_EXIT_CODE".into(),
Value::Int {
val: 0,
span: Span { start: 0, end: 0 },
},
);
info!(
"load config initially {}:{}:{}",
@ -138,7 +149,7 @@ pub fn evaluate_repl(
stack,
s.item.as_bytes(),
&format!("entry #{}", entry_num),
PipelineData::empty(),
PipelineData::new(Span::new(0, 0)),
);
engine_state.merge_env(stack, get_guaranteed_cwd(engine_state, stack))?;
}
@ -172,6 +183,8 @@ pub fn evaluate_repl(
info!("setup colors {}:{}:{}", file!(), line!(), column!());
let color_hm = get_color_config(config);
info!("update reedline {}:{}:{}", file!(), line!(), column!());
let engine_reference = std::sync::Arc::new(engine_state.clone());
line_editor = line_editor
@ -190,14 +203,10 @@ pub fn evaluate_repl(
.with_partial_completions(config.partial_completions)
.with_ansi_colors(config.use_ansi_coloring);
let style_computer = StyleComputer::from_config(engine_state, stack);
line_editor = if config.use_ansi_coloring {
line_editor.with_hinter(Box::new({
// As of Nov 2022, "hints" color_config closures only get `null` passed in.
let style = style_computer.compute("hints", &Value::nothing(Span::unknown()));
DefaultHinter::default().with_style(style)
}))
line_editor.with_hinter(Box::new(
DefaultHinter::default().with_style(color_hm["hints"]),
))
} else {
line_editor.disable_hints()
};
@ -366,7 +375,7 @@ pub fn evaluate_repl(
"OLDPWD".into(),
Value::String {
val: cwd.clone(),
span: Span::unknown(),
span: Span { start: 0, end: 0 },
},
);
@ -376,7 +385,7 @@ pub fn evaluate_repl(
"PWD".into(),
Value::String {
val: path.clone(),
span: Span::unknown(),
span: Span { start: 0, end: 0 },
},
);
let cwd = Value::String { val: cwd, span };
@ -422,7 +431,7 @@ pub fn evaluate_repl(
stack,
s.as_bytes(),
&format!("entry #{}", entry_num),
PipelineData::empty(),
PipelineData::new(Span::new(0, 0)),
);
}
let cmd_duration = start_time.elapsed();
@ -431,7 +440,7 @@ pub fn evaluate_repl(
"CMD_DURATION_MS".into(),
Value::String {
val: format!("{}", cmd_duration.as_millis()),
span: Span::unknown(),
span: Span { start: 0, end: 0 },
},
);
@ -628,7 +637,7 @@ pub fn eval_string_with_input(
let input_as_pipeline_data = match input {
Some(input) => PipelineData::Value(input, None),
None => PipelineData::empty(),
None => PipelineData::new(Span::test_data()),
};
eval_block(
@ -639,7 +648,7 @@ pub fn eval_string_with_input(
false,
true,
)
.map(|x| x.into_value(Span::unknown()))
.map(|x| x.into_value(Span::test_data()))
}
pub fn get_command_finished_marker(stack: &Stack, engine_state: &EngineState) -> String {
@ -709,18 +718,11 @@ pub fn eval_hook(
) -> Result<PipelineData, ShellError> {
let value_span = value.span()?;
// Hooks can optionally be a record in this form:
// {
// condition: {|before, after| ... } # block that evaluates to true/false
// code: # block or a string
// }
// The condition block will be run to check whether the main hook (in `code`) should be run.
// If it returns true (the default if a condition block is not specified), the hook should be run.
let condition_path = PathMember::String {
val: "condition".to_string(),
span: value_span,
};
let mut output = PipelineData::empty();
let mut output = PipelineData::new(Span::new(0, 0));
let code_path = PathMember::String {
val: "code".to_string(),
@ -734,63 +736,57 @@ pub fn eval_hook(
}
}
Value::Record { .. } => {
let do_run_hook = if let Ok(condition) =
value
.clone()
.follow_cell_path(&[condition_path], false, false)
{
match condition {
Value::Block {
val: block_id,
span: block_span,
..
}
| Value::Closure {
val: block_id,
span: block_span,
..
} => {
match run_hook_block(
engine_state,
stack,
block_id,
None,
arguments.clone(),
block_span,
) {
Ok(pipeline_data) => {
if let PipelineData::Value(Value::Bool { val, .. }, ..) =
pipeline_data
{
val
} else {
return Err(ShellError::UnsupportedConfigValue(
"boolean output".to_string(),
"other PipelineData variant".to_string(),
block_span,
));
let do_run_hook =
if let Ok(condition) = value.clone().follow_cell_path(&[condition_path], false) {
match condition {
Value::Block {
val: block_id,
span: block_span,
..
}
| Value::Closure {
val: block_id,
span: block_span,
..
} => {
match run_hook_block(
engine_state,
stack,
block_id,
None,
arguments.clone(),
block_span,
) {
Ok(value) => match value {
Value::Bool { val, .. } => val,
other => {
return Err(ShellError::UnsupportedConfigValue(
"boolean output".to_string(),
format!("{}", other.get_type()),
other.span()?,
));
}
},
Err(err) => {
return Err(err);
}
}
Err(err) => {
return Err(err);
}
}
other => {
return Err(ShellError::UnsupportedConfigValue(
"block".to_string(),
format!("{}", other.get_type()),
other.span()?,
));
}
}
other => {
return Err(ShellError::UnsupportedConfigValue(
"block".to_string(),
format!("{}", other.get_type()),
other.span()?,
));
}
}
} else {
// always run the hook
true
};
} else {
// always run the hook
true
};
if do_run_hook {
match value.clone().follow_cell_path(&[code_path], false, false)? {
match value.clone().follow_cell_path(&[code_path], false)? {
Value::String {
val,
span: source_span,
@ -827,7 +823,7 @@ pub fn eval_hook(
};
engine_state.merge_delta(delta)?;
let input = PipelineData::empty();
let input = PipelineData::new(value_span);
let var_ids: Vec<VarId> = vars
.into_iter()
@ -893,28 +889,34 @@ pub fn eval_hook(
span: block_span,
..
} => {
output = run_hook_block(
engine_state,
stack,
*block_id,
input,
arguments,
*block_span,
)?;
output = PipelineData::Value(
run_hook_block(
engine_state,
stack,
*block_id,
input,
arguments,
*block_span,
)?,
None,
);
}
Value::Closure {
val: block_id,
span: block_span,
..
} => {
output = run_hook_block(
engine_state,
stack,
*block_id,
input,
arguments,
*block_span,
)?;
output = PipelineData::Value(
run_hook_block(
engine_state,
stack,
*block_id,
input,
arguments,
*block_span,
)?,
None,
);
}
other => {
return Err(ShellError::UnsupportedConfigValue(
@ -931,17 +933,17 @@ pub fn eval_hook(
Ok(output)
}
fn run_hook_block(
pub fn run_hook_block(
engine_state: &EngineState,
stack: &mut Stack,
block_id: BlockId,
optional_input: Option<PipelineData>,
arguments: Vec<(String, Value)>,
span: Span,
) -> Result<PipelineData, ShellError> {
) -> Result<Value, ShellError> {
let block = engine_state.get_block(block_id);
let input = optional_input.unwrap_or_else(PipelineData::empty);
let input = optional_input.unwrap_or_else(|| PipelineData::new(span));
let mut callee_stack = stack.gather_captures(&block.captures);
@ -962,28 +964,28 @@ fn run_hook_block(
match eval_block_with_early_return(engine_state, &mut callee_stack, block, input, false, false)
{
Ok(pipeline_data) => {
if let PipelineData::Value(Value::Error { error }, _) = pipeline_data {
return Err(error);
}
Ok(pipeline_data) => match pipeline_data.into_value(span) {
Value::Error { error } => Err(error),
val => {
// If all went fine, preserve the environment of the called block
let caller_env_vars = stack.get_env_var_names(engine_state);
// If all went fine, preserve the environment of the called block
let caller_env_vars = stack.get_env_var_names(engine_state);
// remove env vars that are present in the caller but not in the callee
// (the callee hid them)
for var in caller_env_vars.iter() {
if !callee_stack.has_env_var(engine_state, var) {
stack.remove_env_var(engine_state, var);
// remove env vars that are present in the caller but not in the callee
// (the callee hid them)
for var in caller_env_vars.iter() {
if !callee_stack.has_env_var(engine_state, var) {
stack.remove_env_var(engine_state, var);
}
}
}
// add new env vars from callee to caller
for (var, value) in callee_stack.get_stack_env_vars() {
stack.add_env_var(var, value);
// add new env vars from callee to caller
for (var, value) in callee_stack.get_stack_env_vars() {
stack.add_env_var(var, value);
}
Ok(val)
}
Ok(pipeline_data)
}
},
Err(err) => Err(err),
}
}
@ -995,7 +997,7 @@ fn run_ansi_sequence(seq: &str) -> Result<(), ShellError> {
return Err(ShellError::GenericError(
"Error writing ansi sequence".into(),
err.to_string(),
Some(Span::unknown()),
Some(Span { start: 0, end: 0 }),
None,
Vec::new(),
));
@ -1005,19 +1007,18 @@ fn run_ansi_sequence(seq: &str) -> Result<(), ShellError> {
ShellError::GenericError(
"Error flushing stdio".into(),
e.to_string(),
Some(Span::unknown()),
Some(Span { start: 0, end: 0 }),
None,
Vec::new(),
)
})
}
// Absolute paths with a drive letter, like 'C:', 'D:\', 'E:\foo'
#[cfg(windows)]
static DRIVE_PATH_REGEX: once_cell::sync::Lazy<fancy_regex::Regex> =
once_cell::sync::Lazy::new(|| {
fancy_regex::Regex::new(r"^[a-zA-Z]:[/\\]?").expect("Internal error: regex creation")
});
lazy_static! {
// Absolute paths with a drive letter, like 'C:', 'D:\', 'E:\foo'
static ref DRIVE_PATH_REGEX: Regex =
Regex::new(r"^[a-zA-Z]:[/\\]?").expect("Internal error: regex creation");
}
// A best-effort "does this string look kinda like a path?" function to determine whether to auto-cd
fn looks_like_path(orig: &str) -> bool {

View File

@ -149,7 +149,7 @@ fn split_span_by_highlight_positions(
for pos in highlight_positions {
if start <= *pos && pos < &span.end {
if start < *pos {
result.push((Span::new(start, *pos), false));
result.push((Span { start, end: *pos }, false));
}
let span_str = &line[pos - global_span_offset..span.end - global_span_offset];
let end = span_str
@ -157,12 +157,18 @@ fn split_span_by_highlight_positions(
.next()
.map(|c| pos + get_char_length(c))
.unwrap_or(pos + 1);
result.push((Span::new(*pos, end), true));
result.push((Span { start: *pos, end }, true));
start = end;
}
}
if start < span.end {
result.push((Span::new(start, span.end), false));
result.push((
Span {
start,
end: span.end,
},
false,
));
}
result
}
@ -352,7 +358,6 @@ fn find_matching_block_end_in_expr(
let opt_expr = match arg {
Argument::Named((_, _, opt_expr)) => opt_expr.as_ref(),
Argument::Positional(inner_expr) => Some(inner_expr),
Argument::Unknown(inner_expr) => Some(inner_expr),
};
if let Some(inner_expr) = opt_expr {

View File

@ -250,7 +250,7 @@ pub fn eval_source(
}
}
} else {
result = pipeline_data.print(engine_state, stack, true, false);
result = pipeline_data.print(engine_state, stack, false, false);
}
match result {
@ -289,7 +289,10 @@ pub fn eval_source(
fn set_last_exit_code(stack: &mut Stack, exit_code: i64) {
stack.add_env_var(
"LAST_EXIT_CODE".to_string(),
Value::int(exit_code, Span::unknown()),
Value::Int {
val: exit_code,
span: Span { start: 0, end: 0 },
},
);
}

View File

@ -5,7 +5,7 @@ use nu_parser::parse;
use nu_protocol::engine::StateWorkingSet;
use reedline::{Completer, Suggestion};
use rstest::{fixture, rstest};
use support::{completions_helpers::new_quote_engine, file, folder, match_suggestions, new_engine};
use support::{file, folder, match_suggestions, new_engine};
#[fixture]
fn completer() -> NuCompleter {
@ -34,26 +34,6 @@ fn completer_strings() -> NuCompleter {
NuCompleter::new(std::sync::Arc::new(engine), stack)
}
#[fixture]
fn extern_completer() -> NuCompleter {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
// Add record value as example
let record = r#"
def animals [] { [ "cat", "dog", "eel" ] }
extern spam [
animal: string@animals
--foo (-f): string@animals
-b: string@animals
]
"#;
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
// Instantiate a new completer
NuCompleter::new(std::sync::Arc::new(engine), stack)
}
#[test]
fn variables_dollar_sign_with_varialblecompletion() {
let (_, _, engine, stack) = new_engine();
@ -109,7 +89,7 @@ fn dotnu_completions() {
// Create a new engine
let (_, _, engine, stack) = new_engine();
// Instantiate a new completer
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test source completion
@ -169,7 +149,7 @@ fn file_completions() {
// Create a new engine
let (dir, dir_str, engine, stack) = new_engine();
// Instantiate a new completer
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for the current folder
@ -431,36 +411,17 @@ fn command_watch_with_filecompletion() {
match_suggestions(expected_paths, suggestions)
}
#[test]
fn file_completion_quoted() {
let (_, _, engine, stack) = new_quote_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "open ";
let suggestions = completer.complete(target_dir, target_dir.len());
let expected_paths: Vec<String> = vec![
"`te st.txt`".to_string(),
"`te#st.txt`".to_string(),
"`te'st.txt`".to_string(),
"`te(st).txt`".to_string(),
];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn flag_completions() {
// Create a new engine
let (_, _, engine, stack) = new_engine();
// Instantiate a new completer
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for the 'ls' flags
let suggestions = completer.complete("ls -", 4);
assert_eq!(16, suggestions.len());
assert_eq!(14, suggestions.len());
let expected: Vec<String> = vec![
"--all".into(),
@ -469,7 +430,6 @@ fn flag_completions() {
"--full-paths".into(),
"--help".into(),
"--long".into(),
"--mime-type".into(),
"--short-names".into(),
"-D".into(),
"-a".into(),
@ -477,7 +437,6 @@ fn flag_completions() {
"-f".into(),
"-h".into(),
"-l".into(),
"-m".into(),
"-s".into(),
];
@ -490,7 +449,7 @@ fn folder_with_directorycompletions() {
// Create a new engine
let (dir, dir_str, engine, stack) = new_engine();
// Instantiate a new completer
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for the current folder
@ -518,7 +477,7 @@ fn variables_completions() {
let record = "let actor = { name: 'Tom Hardy', age: 44 }";
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
// Instantiate a new completer
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for $nu
@ -675,7 +634,7 @@ fn run_external_completion(block: &str, input: &str) -> Vec<Suggestion> {
config.external_completer = Some(latest_block_id);
engine_state.set_config(&config);
// Instantiate a new completer
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine_state), stack);
completer.complete(input, input.len())
@ -773,45 +732,3 @@ fn filecompletions_triggers_after_cursor() {
match_suggestions(expected_paths, suggestions);
}
#[rstest]
fn extern_custom_completion_positional(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam ", 5);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn extern_custom_completion_long_flag_1(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam --foo=", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn extern_custom_completion_long_flag_2(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam --foo ", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn extern_custom_completion_long_flag_short(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam -f ", 8);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn extern_custom_completion_short_flag(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam -b ", 8);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn extern_complete_flags(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam -", 6);
let expected: Vec<String> = vec!["--foo".into(), "-b".into(), "-f".into()];
match_suggestions(expected, suggestions);
}

View File

@ -33,53 +33,20 @@ pub fn new_engine() -> (PathBuf, String, EngineState, Stack) {
"PWD".to_string(),
Value::String {
val: dir_str.clone(),
span: nu_protocol::Span::new(0, dir_str.len()),
span: nu_protocol::Span {
start: 0,
end: dir_str.len(),
},
},
);
stack.add_env_var(
"TEST".to_string(),
Value::String {
val: "NUSHELL".to_string(),
span: nu_protocol::Span::new(0, dir_str.len()),
},
);
// Merge environment into the permanent state
let merge_result = engine_state.merge_env(&mut stack, &dir);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
}
pub fn new_quote_engine() -> (PathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("quoted_completions");
let mut dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
dir_str.push(SEP);
// Create a new engine with default context
let mut engine_state = create_default_context();
// New stack
let mut stack = Stack::new();
// Add pwd as env var
stack.add_env_var(
"PWD".to_string(),
Value::String {
val: dir_str.clone(),
span: nu_protocol::Span::new(0, dir_str.len()),
},
);
stack.add_env_var(
"TEST".to_string(),
Value::String {
val: "NUSHELL".to_string(),
span: nu_protocol::Span::new(0, dir_str.len()),
span: nu_protocol::Span {
start: 0,
end: dir_str.len(),
},
},
);
@ -145,7 +112,7 @@ pub fn merge_input(
&block,
PipelineData::Value(
Value::Nothing {
span: Span::unknown(),
span: Span { start: 0, end: 0 },
},
None
),

View File

@ -5,18 +5,11 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-color-confi
edition = "2021"
license = "MIT"
name = "nu-color-config"
version = "0.74.0"
version = "0.72.1"
[dependencies]
serde = { version="1.0.123", features=["derive"] }
# used only for text_style Alignments
tabled = { version = "0.10.0", features = ["color"], default-features = false }
nu-protocol = { path = "../nu-protocol", version = "0.74.0" }
nu-protocol = { path = "../nu-protocol", version = "0.72.1" }
nu-ansi-term = "0.46.0"
nu-utils = { path = "../nu-utils", version = "0.74.0" }
nu-engine = { path = "../nu-engine", version = "0.74.0" }
nu-json = { path="../nu-json", version = "0.74.0" }
[dev-dependencies]
nu-test-support = { path="../nu-test-support", version = "0.74.0" }
nu-json = { path = "../nu-json", version = "0.72.1" }
nu-table = { path = "../nu-table", version = "0.72.1" }
serde = { version="1.0.123", features=["derive"] }

View File

@ -1,89 +1,413 @@
use crate::{
nu_style::{color_from_hex, lookup_style},
parse_nustyle, NuStyle,
};
use nu_ansi_term::Style;
use nu_protocol::Value;
use crate::nu_style::{color_from_hex, color_string_to_nustyle};
use nu_ansi_term::{Color, Style};
use nu_protocol::Config;
use nu_table::{Alignment, TextStyle};
use std::collections::HashMap;
pub fn lookup_ansi_color_style(s: &str) -> Style {
if s.starts_with('#') {
color_from_hex(s)
.ok()
.and_then(|c| c.map(|c| c.normal()))
.unwrap_or_default()
match color_from_hex(s) {
Ok(c) => match c {
Some(c) => c.normal(),
None => Style::default(),
},
Err(_) => Style::default(),
}
} else if s.starts_with('{') {
color_string_to_nustyle(s.to_string())
} else {
lookup_style(s)
match s {
"g" | "green" => Color::Green.normal(),
"gb" | "green_bold" => Color::Green.bold(),
"gu" | "green_underline" => Color::Green.underline(),
"gi" | "green_italic" => Color::Green.italic(),
"gd" | "green_dimmed" => Color::Green.dimmed(),
"gr" | "green_reverse" => Color::Green.reverse(),
"gbl" | "green_blink" => Color::Green.blink(),
"gst" | "green_strike" => Color::Green.strikethrough(),
"lg" | "light_green" => Color::LightGreen.normal(),
"lgb" | "light_green_bold" => Color::LightGreen.bold(),
"lgu" | "light_green_underline" => Color::LightGreen.underline(),
"lgi" | "light_green_italic" => Color::LightGreen.italic(),
"lgd" | "light_green_dimmed" => Color::LightGreen.dimmed(),
"lgr" | "light_green_reverse" => Color::LightGreen.reverse(),
"lgbl" | "light_green_blink" => Color::LightGreen.blink(),
"lgst" | "light_green_strike" => Color::LightGreen.strikethrough(),
"r" | "red" => Color::Red.normal(),
"rb" | "red_bold" => Color::Red.bold(),
"ru" | "red_underline" => Color::Red.underline(),
"ri" | "red_italic" => Color::Red.italic(),
"rd" | "red_dimmed" => Color::Red.dimmed(),
"rr" | "red_reverse" => Color::Red.reverse(),
"rbl" | "red_blink" => Color::Red.blink(),
"rst" | "red_strike" => Color::Red.strikethrough(),
"lr" | "light_red" => Color::LightRed.normal(),
"lrb" | "light_red_bold" => Color::LightRed.bold(),
"lru" | "light_red_underline" => Color::LightRed.underline(),
"lri" | "light_red_italic" => Color::LightRed.italic(),
"lrd" | "light_red_dimmed" => Color::LightRed.dimmed(),
"lrr" | "light_red_reverse" => Color::LightRed.reverse(),
"lrbl" | "light_red_blink" => Color::LightRed.blink(),
"lrst" | "light_red_strike" => Color::LightRed.strikethrough(),
"u" | "blue" => Color::Blue.normal(),
"ub" | "blue_bold" => Color::Blue.bold(),
"uu" | "blue_underline" => Color::Blue.underline(),
"ui" | "blue_italic" => Color::Blue.italic(),
"ud" | "blue_dimmed" => Color::Blue.dimmed(),
"ur" | "blue_reverse" => Color::Blue.reverse(),
"ubl" | "blue_blink" => Color::Blue.blink(),
"ust" | "blue_strike" => Color::Blue.strikethrough(),
"lu" | "light_blue" => Color::LightBlue.normal(),
"lub" | "light_blue_bold" => Color::LightBlue.bold(),
"luu" | "light_blue_underline" => Color::LightBlue.underline(),
"lui" | "light_blue_italic" => Color::LightBlue.italic(),
"lud" | "light_blue_dimmed" => Color::LightBlue.dimmed(),
"lur" | "light_blue_reverse" => Color::LightBlue.reverse(),
"lubl" | "light_blue_blink" => Color::LightBlue.blink(),
"lust" | "light_blue_strike" => Color::LightBlue.strikethrough(),
"b" | "black" => Color::Black.normal(),
"bb" | "black_bold" => Color::Black.bold(),
"bu" | "black_underline" => Color::Black.underline(),
"bi" | "black_italic" => Color::Black.italic(),
"bd" | "black_dimmed" => Color::Black.dimmed(),
"br" | "black_reverse" => Color::Black.reverse(),
"bbl" | "black_blink" => Color::Black.blink(),
"bst" | "black_strike" => Color::Black.strikethrough(),
"ligr" | "light_gray" => Color::LightGray.normal(),
"ligrb" | "light_gray_bold" => Color::LightGray.bold(),
"ligru" | "light_gray_underline" => Color::LightGray.underline(),
"ligri" | "light_gray_italic" => Color::LightGray.italic(),
"ligrd" | "light_gray_dimmed" => Color::LightGray.dimmed(),
"ligrr" | "light_gray_reverse" => Color::LightGray.reverse(),
"ligrbl" | "light_gray_blink" => Color::LightGray.blink(),
"ligrst" | "light_gray_strike" => Color::LightGray.strikethrough(),
"y" | "yellow" => Color::Yellow.normal(),
"yb" | "yellow_bold" => Color::Yellow.bold(),
"yu" | "yellow_underline" => Color::Yellow.underline(),
"yi" | "yellow_italic" => Color::Yellow.italic(),
"yd" | "yellow_dimmed" => Color::Yellow.dimmed(),
"yr" | "yellow_reverse" => Color::Yellow.reverse(),
"ybl" | "yellow_blink" => Color::Yellow.blink(),
"yst" | "yellow_strike" => Color::Yellow.strikethrough(),
"ly" | "light_yellow" => Color::LightYellow.normal(),
"lyb" | "light_yellow_bold" => Color::LightYellow.bold(),
"lyu" | "light_yellow_underline" => Color::LightYellow.underline(),
"lyi" | "light_yellow_italic" => Color::LightYellow.italic(),
"lyd" | "light_yellow_dimmed" => Color::LightYellow.dimmed(),
"lyr" | "light_yellow_reverse" => Color::LightYellow.reverse(),
"lybl" | "light_yellow_blink" => Color::LightYellow.blink(),
"lyst" | "light_yellow_strike" => Color::LightYellow.strikethrough(),
"p" | "purple" => Color::Purple.normal(),
"pb" | "purple_bold" => Color::Purple.bold(),
"pu" | "purple_underline" => Color::Purple.underline(),
"pi" | "purple_italic" => Color::Purple.italic(),
"pd" | "purple_dimmed" => Color::Purple.dimmed(),
"pr" | "purple_reverse" => Color::Purple.reverse(),
"pbl" | "purple_blink" => Color::Purple.blink(),
"pst" | "purple_strike" => Color::Purple.strikethrough(),
"lp" | "light_purple" => Color::LightPurple.normal(),
"lpb" | "light_purple_bold" => Color::LightPurple.bold(),
"lpu" | "light_purple_underline" => Color::LightPurple.underline(),
"lpi" | "light_purple_italic" => Color::LightPurple.italic(),
"lpd" | "light_purple_dimmed" => Color::LightPurple.dimmed(),
"lpr" | "light_purple_reverse" => Color::LightPurple.reverse(),
"lpbl" | "light_purple_blink" => Color::LightPurple.blink(),
"lpst" | "light_purple_strike" => Color::LightPurple.strikethrough(),
"c" | "cyan" => Color::Cyan.normal(),
"cb" | "cyan_bold" => Color::Cyan.bold(),
"cu" | "cyan_underline" => Color::Cyan.underline(),
"ci" | "cyan_italic" => Color::Cyan.italic(),
"cd" | "cyan_dimmed" => Color::Cyan.dimmed(),
"cr" | "cyan_reverse" => Color::Cyan.reverse(),
"cbl" | "cyan_blink" => Color::Cyan.blink(),
"cst" | "cyan_strike" => Color::Cyan.strikethrough(),
"lc" | "light_cyan" => Color::LightCyan.normal(),
"lcb" | "light_cyan_bold" => Color::LightCyan.bold(),
"lcu" | "light_cyan_underline" => Color::LightCyan.underline(),
"lci" | "light_cyan_italic" => Color::LightCyan.italic(),
"lcd" | "light_cyan_dimmed" => Color::LightCyan.dimmed(),
"lcr" | "light_cyan_reverse" => Color::LightCyan.reverse(),
"lcbl" | "light_cyan_blink" => Color::LightCyan.blink(),
"lcst" | "light_cyan_strike" => Color::LightCyan.strikethrough(),
"w" | "white" => Color::White.normal(),
"wb" | "white_bold" => Color::White.bold(),
"wu" | "white_underline" => Color::White.underline(),
"wi" | "white_italic" => Color::White.italic(),
"wd" | "white_dimmed" => Color::White.dimmed(),
"wr" | "white_reverse" => Color::White.reverse(),
"wbl" | "white_blink" => Color::White.blink(),
"wst" | "white_strike" => Color::White.strikethrough(),
"dgr" | "dark_gray" => Color::DarkGray.normal(),
"dgrb" | "dark_gray_bold" => Color::DarkGray.bold(),
"dgru" | "dark_gray_underline" => Color::DarkGray.underline(),
"dgri" | "dark_gray_italic" => Color::DarkGray.italic(),
"dgrd" | "dark_gray_dimmed" => Color::DarkGray.dimmed(),
"dgrr" | "dark_gray_reverse" => Color::DarkGray.reverse(),
"dgrbl" | "dark_gray_blink" => Color::DarkGray.blink(),
"dgrst" | "dark_gray_strike" => Color::DarkGray.strikethrough(),
"def" | "default" => Color::Default.normal(),
"defb" | "default_bold" => Color::Default.bold(),
"defu" | "default_underline" => Color::Default.underline(),
"defi" | "default_italic" => Color::Default.italic(),
"defd" | "default_dimmed" => Color::Default.dimmed(),
"defr" | "default_reverse" => Color::Default.reverse(),
_ => Color::White.normal(),
}
}
}
pub fn get_color_map(colors: &HashMap<String, Value>) -> HashMap<String, Style> {
let mut hm: HashMap<String, Style> = HashMap::new();
fn update_hashmap(key: &str, val: &str, hm: &mut HashMap<String, Style>) {
// eprintln!("key: {}, val: {}", &key, &val);
let color = lookup_ansi_color_style(val);
if let Some(v) = hm.get_mut(key) {
*v = color;
} else {
hm.insert(key.to_string(), color);
}
}
for (key, value) in colors {
parse_map_entry(&mut hm, key, value);
pub fn get_color_config(config: &Config) -> HashMap<String, Style> {
let config = config;
// create the hashmap
let mut hm: HashMap<String, Style> = HashMap::new();
// set some defaults
// hm.insert("primitive_line".to_string(), Color::White.normal());
// hm.insert("primitive_pattern".to_string(), Color::White.normal());
// hm.insert("primitive_path".to_string(), Color::White.normal());
hm.insert("separator".to_string(), Color::White.normal());
hm.insert(
"leading_trailing_space_bg".to_string(),
Style::default().on(Color::Rgb(128, 128, 128)),
);
hm.insert("header".to_string(), Color::Green.bold());
hm.insert("empty".to_string(), Color::Blue.normal());
hm.insert("bool".to_string(), Color::White.normal());
hm.insert("int".to_string(), Color::White.normal());
hm.insert("filesize".to_string(), Color::White.normal());
hm.insert("duration".to_string(), Color::White.normal());
hm.insert("date".to_string(), Color::White.normal());
hm.insert("range".to_string(), Color::White.normal());
hm.insert("float".to_string(), Color::White.normal());
hm.insert("string".to_string(), Color::White.normal());
hm.insert("nothing".to_string(), Color::White.normal());
hm.insert("binary".to_string(), Color::White.normal());
hm.insert("cellpath".to_string(), Color::White.normal());
hm.insert("row_index".to_string(), Color::Green.bold());
hm.insert("record".to_string(), Color::White.normal());
hm.insert("list".to_string(), Color::White.normal());
hm.insert("block".to_string(), Color::White.normal());
hm.insert("hints".to_string(), Color::DarkGray.normal());
for (key, value) in &config.color_config {
match value.as_string() {
Ok(value) => update_hashmap(key, &value, &mut hm),
Err(_) => continue,
}
}
hm
}
fn parse_map_entry(hm: &mut HashMap<String, Style>, key: &str, value: &Value) {
let value = match value {
Value::String { val, .. } => Some(lookup_ansi_color_style(val)),
Value::Record { cols, vals, .. } => get_style_from_value(cols, vals).map(parse_nustyle),
_ => None,
};
if let Some(value) = value {
hm.entry(key.to_owned()).or_insert(value);
}
}
fn get_style_from_value(cols: &[String], vals: &[Value]) -> Option<NuStyle> {
let mut was_set = false;
let mut style = NuStyle::from(Style::default());
for (col, val) in cols.iter().zip(vals) {
match col.as_str() {
"bg" => {
if let Value::String { val, .. } = val {
style.bg = Some(val.clone());
was_set = true;
}
// This function will assign a text style to a primitive, or really any string that's
// in the hashmap. The hashmap actually contains the style to be applied.
pub fn style_primitive(primitive: &str, color_hm: &HashMap<String, Style>) -> TextStyle {
match primitive {
"bool" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Left, *s),
None => TextStyle::basic_left(),
}
"fg" => {
if let Value::String { val, .. } = val {
style.fg = Some(val.clone());
was_set = true;
}
}
"attr" => {
if let Value::String { val, .. } = val {
style.attr = Some(val.clone());
was_set = true;
}
}
_ => (),
}
}
if was_set {
Some(style)
} else {
None
"int" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Right, *s),
None => TextStyle::basic_right(),
}
}
"filesize" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Right, *s),
None => TextStyle::basic_right(),
}
}
"duration" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Left, *s),
None => TextStyle::basic_left(),
}
}
"date" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Left, *s),
None => TextStyle::basic_left(),
}
}
"range" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Left, *s),
None => TextStyle::basic_left(),
}
}
"float" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Right, *s),
None => TextStyle::basic_right(),
}
}
"string" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Left, *s),
None => TextStyle::basic_left(),
}
}
"nothing" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Left, *s),
None => TextStyle::basic_left(),
}
}
// not sure what to do with error
// "error" => {}
"binary" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Left, *s),
None => TextStyle::basic_left(),
}
}
"cellpath" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Left, *s),
None => TextStyle::basic_left(),
}
}
"row_index" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Right, *s),
None => TextStyle::new()
.alignment(Alignment::Right)
.fg(Color::Green)
.bold(Some(true)),
}
}
"record" | "list" | "block" => {
let style = color_hm.get(primitive);
match style {
Some(s) => TextStyle::with_style(Alignment::Left, *s),
None => TextStyle::basic_left(),
}
}
// types in nushell but not in engine-q
// "Line" => {
// let style = color_hm.get("Primitive::Line");
// match style {
// Some(s) => TextStyle::with_style(Alignment::Left, *s),
// None => TextStyle::basic_left(),
// }
// }
// "GlobPattern" => {
// let style = color_hm.get("Primitive::GlobPattern");
// match style {
// Some(s) => TextStyle::with_style(Alignment::Left, *s),
// None => TextStyle::basic_left(),
// }
// }
// "FilePath" => {
// let style = color_hm.get("Primitive::FilePath");
// match style {
// Some(s) => TextStyle::with_style(Alignment::Left, *s),
// None => TextStyle::basic_left(),
// }
// }
// "BeginningOfStream" => {
// let style = color_hm.get("Primitive::BeginningOfStream");
// match style {
// Some(s) => TextStyle::with_style(Alignment::Left, *s),
// None => TextStyle::basic_left(),
// }
// }
// "EndOfStream" => {
// let style = color_hm.get("Primitive::EndOfStream");
// match style {
// Some(s) => TextStyle::with_style(Alignment::Left, *s),
// None => TextStyle::basic_left(),
// }
// }
_ => TextStyle::basic_left(),
}
}
fn color_string_to_nustyle(color_string: String) -> Style {
// eprintln!("color_string: {}", &color_string);
if color_string.is_empty() {
return Style::default();
}
#[test]
fn test_hm() {
use nu_ansi_term::{Color, Style};
let nu_style = match nu_json::from_str::<NuStyle>(&color_string) {
Ok(s) => s,
Err(_) => return Style::default(),
};
let mut hm: HashMap<String, Style> = HashMap::new();
hm.insert("primitive_int".to_string(), Color::White.normal());
hm.insert("primitive_decimal".to_string(), Color::White.normal());
hm.insert("primitive_filesize".to_string(), Color::White.normal());
hm.insert("primitive_string".to_string(), Color::White.normal());
hm.insert("primitive_line".to_string(), Color::White.normal());
hm.insert("primitive_columnpath".to_string(), Color::White.normal());
hm.insert("primitive_pattern".to_string(), Color::White.normal());
hm.insert("primitive_boolean".to_string(), Color::White.normal());
hm.insert("primitive_date".to_string(), Color::White.normal());
hm.insert("primitive_duration".to_string(), Color::White.normal());
hm.insert("primitive_range".to_string(), Color::White.normal());
hm.insert("primitive_path".to_string(), Color::White.normal());
hm.insert("primitive_binary".to_string(), Color::White.normal());
hm.insert("separator".to_string(), Color::White.normal());
hm.insert("header_align".to_string(), Color::Green.bold());
hm.insert("header".to_string(), Color::Green.bold());
hm.insert("header_style".to_string(), Style::default());
hm.insert("row_index".to_string(), Color::Green.bold());
hm.insert(
"leading_trailing_space_bg".to_string(),
Style::default().on(Color::Rgb(128, 128, 128)),
);
parse_nustyle(nu_style)
update_hashmap("primitive_int", "green", &mut hm);
assert_eq!(hm["primitive_int"], Color::Green.normal());
}

View File

@ -2,12 +2,8 @@ mod color_config;
mod matching_brackets_style;
mod nu_style;
mod shape_color;
mod style_computer;
mod text_style;
pub use color_config::*;
pub use matching_brackets_style::*;
pub use nu_style::*;
pub use shape_color::*;
pub use style_computer::*;
pub use text_style::*;

View File

@ -1,113 +1,88 @@
use nu_ansi_term::{Color, Style};
use nu_protocol::Value;
use serde::{Deserialize, Serialize};
use serde::Deserialize;
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]
#[derive(Deserialize, PartialEq, Eq, Debug)]
pub struct NuStyle {
pub fg: Option<String>,
pub bg: Option<String>,
pub attr: Option<String>,
}
impl From<Style> for NuStyle {
fn from(s: Style) -> Self {
Self {
bg: s.background.and_then(color_to_string),
fg: s.foreground.and_then(color_to_string),
attr: style_get_attr(s),
}
}
}
fn style_get_attr(s: Style) -> Option<String> {
macro_rules! check {
($attrs:expr, $b:expr, $c:expr) => {
if $b {
$attrs.push($c);
}
};
}
let mut attrs = String::new();
check!(attrs, s.is_blink, 'l');
check!(attrs, s.is_bold, 'b');
check!(attrs, s.is_dimmed, 'd');
check!(attrs, s.is_reverse, 'r');
check!(attrs, s.is_strikethrough, 's');
check!(attrs, s.is_underline, 'u');
if attrs.is_empty() {
None
} else {
Some(attrs)
}
}
fn color_to_string(color: Color) -> Option<String> {
match color {
Color::Black => Some(String::from("black")),
Color::DarkGray => Some(String::from("dark_gray")),
Color::Red => Some(String::from("red")),
Color::LightRed => Some(String::from("light_red")),
Color::Green => Some(String::from("green")),
Color::LightGreen => Some(String::from("light_green")),
Color::Yellow => Some(String::from("yellow")),
Color::LightYellow => Some(String::from("light_yellow")),
Color::Blue => Some(String::from("blue")),
Color::LightBlue => Some(String::from("light_blue")),
Color::Purple => Some(String::from("purple")),
Color::LightPurple => Some(String::from("light_purple")),
Color::Magenta => Some(String::from("magenta")),
Color::LightMagenta => Some(String::from("light_magenta")),
Color::Cyan => Some(String::from("cyan")),
Color::LightCyan => Some(String::from("light_cyan")),
Color::White => Some(String::from("white")),
Color::LightGray => Some(String::from("light_gray")),
Color::Default => Some(String::from("default")),
Color::Rgb(r, g, b) => Some(format!("#{:X}{:X}{:X}", r, g, b)),
Color::Fixed(_) => None,
}
}
pub fn parse_nustyle(nu_style: NuStyle) -> Style {
let mut style = Style {
foreground: nu_style.fg.and_then(|fg| lookup_color_str(&fg)),
background: nu_style.bg.and_then(|bg| lookup_color_str(&bg)),
..Default::default()
// get the nu_ansi_term::Color foreground color
let fg_color = match nu_style.fg {
Some(fg) => color_from_hex(&fg).unwrap_or_default(),
_ => None,
};
// get the nu_ansi_term::Color background color
let bg_color = match nu_style.bg {
Some(bg) => color_from_hex(&bg).unwrap_or_default(),
_ => None,
};
// get the attributes
let color_attr = match nu_style.attr {
Some(attr) => attr,
_ => "".to_string(),
};
if let Some(attrs) = nu_style.attr {
fill_modifiers(&attrs, &mut style)
}
// setup the attributes available in nu_ansi_term::Style
let mut bold = false;
let mut dimmed = false;
let mut italic = false;
let mut underline = false;
let mut blink = false;
let mut reverse = false;
let mut hidden = false;
let mut strikethrough = false;
style
}
// Converts the color_config records, { fg, bg, attr }, into a Style.
pub fn color_record_to_nustyle(value: &Value) -> Style {
let mut fg = None;
let mut bg = None;
let mut attr = None;
let v = value.as_record();
if let Ok((cols, inner_vals)) = v {
for (k, v) in cols.iter().zip(inner_vals) {
// Because config already type-checked the color_config records, this doesn't bother giving errors
// if there are unrecognised keys or bad values.
if let Ok(v) = v.as_string() {
match k.as_str() {
"fg" => fg = Some(v),
"bg" => bg = Some(v),
"attr" => attr = Some(v),
_ => (),
}
}
// since we can combine styles like bold-italic, iterate through the chars
// and set the bools for later use in the nu_ansi_term::Style application
for ch in color_attr.to_lowercase().chars() {
match ch {
'l' => blink = true,
'b' => bold = true,
'd' => dimmed = true,
'h' => hidden = true,
'i' => italic = true,
'r' => reverse = true,
's' => strikethrough = true,
'u' => underline = true,
'n' => (),
_ => (),
}
}
parse_nustyle(NuStyle { fg, bg, attr })
// here's where we build the nu_ansi_term::Style
Style {
foreground: fg_color,
background: bg_color,
is_blink: blink,
is_bold: bold,
is_dimmed: dimmed,
is_hidden: hidden,
is_italic: italic,
is_reverse: reverse,
is_strikethrough: strikethrough,
is_underline: underline,
}
}
pub fn color_string_to_nustyle(color_string: String) -> Style {
// eprintln!("color_string: {}", &color_string);
if color_string.chars().count() < 1 {
Style::default()
} else {
let nu_style = match nu_json::from_str::<NuStyle>(&color_string) {
Ok(s) => s,
Err(_) => NuStyle {
fg: None,
bg: None,
attr: None,
},
};
parse_nustyle(nu_style)
}
}
pub fn color_from_hex(
@ -126,471 +101,3 @@ pub fn color_from_hex(
)))
}
}
pub fn lookup_style(s: &str) -> Style {
match s {
"g" | "green" => Color::Green.normal(),
"gb" | "green_bold" => Color::Green.bold(),
"gu" | "green_underline" => Color::Green.underline(),
"gi" | "green_italic" => Color::Green.italic(),
"gd" | "green_dimmed" => Color::Green.dimmed(),
"gr" | "green_reverse" => Color::Green.reverse(),
"gbl" | "green_blink" => Color::Green.blink(),
"gst" | "green_strike" => Color::Green.strikethrough(),
"lg" | "light_green" => Color::LightGreen.normal(),
"lgb" | "light_green_bold" => Color::LightGreen.bold(),
"lgu" | "light_green_underline" => Color::LightGreen.underline(),
"lgi" | "light_green_italic" => Color::LightGreen.italic(),
"lgd" | "light_green_dimmed" => Color::LightGreen.dimmed(),
"lgr" | "light_green_reverse" => Color::LightGreen.reverse(),
"lgbl" | "light_green_blink" => Color::LightGreen.blink(),
"lgst" | "light_green_strike" => Color::LightGreen.strikethrough(),
"r" | "red" => Color::Red.normal(),
"rb" | "red_bold" => Color::Red.bold(),
"ru" | "red_underline" => Color::Red.underline(),
"ri" | "red_italic" => Color::Red.italic(),
"rd" | "red_dimmed" => Color::Red.dimmed(),
"rr" | "red_reverse" => Color::Red.reverse(),
"rbl" | "red_blink" => Color::Red.blink(),
"rst" | "red_strike" => Color::Red.strikethrough(),
"lr" | "light_red" => Color::LightRed.normal(),
"lrb" | "light_red_bold" => Color::LightRed.bold(),
"lru" | "light_red_underline" => Color::LightRed.underline(),
"lri" | "light_red_italic" => Color::LightRed.italic(),
"lrd" | "light_red_dimmed" => Color::LightRed.dimmed(),
"lrr" | "light_red_reverse" => Color::LightRed.reverse(),
"lrbl" | "light_red_blink" => Color::LightRed.blink(),
"lrst" | "light_red_strike" => Color::LightRed.strikethrough(),
"u" | "blue" => Color::Blue.normal(),
"ub" | "blue_bold" => Color::Blue.bold(),
"uu" | "blue_underline" => Color::Blue.underline(),
"ui" | "blue_italic" => Color::Blue.italic(),
"ud" | "blue_dimmed" => Color::Blue.dimmed(),
"ur" | "blue_reverse" => Color::Blue.reverse(),
"ubl" | "blue_blink" => Color::Blue.blink(),
"ust" | "blue_strike" => Color::Blue.strikethrough(),
"lu" | "light_blue" => Color::LightBlue.normal(),
"lub" | "light_blue_bold" => Color::LightBlue.bold(),
"luu" | "light_blue_underline" => Color::LightBlue.underline(),
"lui" | "light_blue_italic" => Color::LightBlue.italic(),
"lud" | "light_blue_dimmed" => Color::LightBlue.dimmed(),
"lur" | "light_blue_reverse" => Color::LightBlue.reverse(),
"lubl" | "light_blue_blink" => Color::LightBlue.blink(),
"lust" | "light_blue_strike" => Color::LightBlue.strikethrough(),
"b" | "black" => Color::Black.normal(),
"bb" | "black_bold" => Color::Black.bold(),
"bu" | "black_underline" => Color::Black.underline(),
"bi" | "black_italic" => Color::Black.italic(),
"bd" | "black_dimmed" => Color::Black.dimmed(),
"br" | "black_reverse" => Color::Black.reverse(),
"bbl" | "black_blink" => Color::Black.blink(),
"bst" | "black_strike" => Color::Black.strikethrough(),
"ligr" | "light_gray" => Color::LightGray.normal(),
"ligrb" | "light_gray_bold" => Color::LightGray.bold(),
"ligru" | "light_gray_underline" => Color::LightGray.underline(),
"ligri" | "light_gray_italic" => Color::LightGray.italic(),
"ligrd" | "light_gray_dimmed" => Color::LightGray.dimmed(),
"ligrr" | "light_gray_reverse" => Color::LightGray.reverse(),
"ligrbl" | "light_gray_blink" => Color::LightGray.blink(),
"ligrst" | "light_gray_strike" => Color::LightGray.strikethrough(),
"y" | "yellow" => Color::Yellow.normal(),
"yb" | "yellow_bold" => Color::Yellow.bold(),
"yu" | "yellow_underline" => Color::Yellow.underline(),
"yi" | "yellow_italic" => Color::Yellow.italic(),
"yd" | "yellow_dimmed" => Color::Yellow.dimmed(),
"yr" | "yellow_reverse" => Color::Yellow.reverse(),
"ybl" | "yellow_blink" => Color::Yellow.blink(),
"yst" | "yellow_strike" => Color::Yellow.strikethrough(),
"ly" | "light_yellow" => Color::LightYellow.normal(),
"lyb" | "light_yellow_bold" => Color::LightYellow.bold(),
"lyu" | "light_yellow_underline" => Color::LightYellow.underline(),
"lyi" | "light_yellow_italic" => Color::LightYellow.italic(),
"lyd" | "light_yellow_dimmed" => Color::LightYellow.dimmed(),
"lyr" | "light_yellow_reverse" => Color::LightYellow.reverse(),
"lybl" | "light_yellow_blink" => Color::LightYellow.blink(),
"lyst" | "light_yellow_strike" => Color::LightYellow.strikethrough(),
"p" | "purple" => Color::Purple.normal(),
"pb" | "purple_bold" => Color::Purple.bold(),
"pu" | "purple_underline" => Color::Purple.underline(),
"pi" | "purple_italic" => Color::Purple.italic(),
"pd" | "purple_dimmed" => Color::Purple.dimmed(),
"pr" | "purple_reverse" => Color::Purple.reverse(),
"pbl" | "purple_blink" => Color::Purple.blink(),
"pst" | "purple_strike" => Color::Purple.strikethrough(),
"lp" | "light_purple" => Color::LightPurple.normal(),
"lpb" | "light_purple_bold" => Color::LightPurple.bold(),
"lpu" | "light_purple_underline" => Color::LightPurple.underline(),
"lpi" | "light_purple_italic" => Color::LightPurple.italic(),
"lpd" | "light_purple_dimmed" => Color::LightPurple.dimmed(),
"lpr" | "light_purple_reverse" => Color::LightPurple.reverse(),
"lpbl" | "light_purple_blink" => Color::LightPurple.blink(),
"lpst" | "light_purple_strike" => Color::LightPurple.strikethrough(),
"c" | "cyan" => Color::Cyan.normal(),
"cb" | "cyan_bold" => Color::Cyan.bold(),
"cu" | "cyan_underline" => Color::Cyan.underline(),
"ci" | "cyan_italic" => Color::Cyan.italic(),
"cd" | "cyan_dimmed" => Color::Cyan.dimmed(),
"cr" | "cyan_reverse" => Color::Cyan.reverse(),
"cbl" | "cyan_blink" => Color::Cyan.blink(),
"cst" | "cyan_strike" => Color::Cyan.strikethrough(),
"lc" | "light_cyan" => Color::LightCyan.normal(),
"lcb" | "light_cyan_bold" => Color::LightCyan.bold(),
"lcu" | "light_cyan_underline" => Color::LightCyan.underline(),
"lci" | "light_cyan_italic" => Color::LightCyan.italic(),
"lcd" | "light_cyan_dimmed" => Color::LightCyan.dimmed(),
"lcr" | "light_cyan_reverse" => Color::LightCyan.reverse(),
"lcbl" | "light_cyan_blink" => Color::LightCyan.blink(),
"lcst" | "light_cyan_strike" => Color::LightCyan.strikethrough(),
"w" | "white" => Color::White.normal(),
"wb" | "white_bold" => Color::White.bold(),
"wu" | "white_underline" => Color::White.underline(),
"wi" | "white_italic" => Color::White.italic(),
"wd" | "white_dimmed" => Color::White.dimmed(),
"wr" | "white_reverse" => Color::White.reverse(),
"wbl" | "white_blink" => Color::White.blink(),
"wst" | "white_strike" => Color::White.strikethrough(),
"dgr" | "dark_gray" => Color::DarkGray.normal(),
"dgrb" | "dark_gray_bold" => Color::DarkGray.bold(),
"dgru" | "dark_gray_underline" => Color::DarkGray.underline(),
"dgri" | "dark_gray_italic" => Color::DarkGray.italic(),
"dgrd" | "dark_gray_dimmed" => Color::DarkGray.dimmed(),
"dgrr" | "dark_gray_reverse" => Color::DarkGray.reverse(),
"dgrbl" | "dark_gray_blink" => Color::DarkGray.blink(),
"dgrst" | "dark_gray_strike" => Color::DarkGray.strikethrough(),
"def" | "default" => Color::Default.normal(),
"defb" | "default_bold" => Color::Default.bold(),
"defu" | "default_underline" => Color::Default.underline(),
"defi" | "default_italic" => Color::Default.italic(),
"defd" | "default_dimmed" => Color::Default.dimmed(),
"defr" | "default_reverse" => Color::Default.reverse(),
// Add xterm 256 colors adding an x prefix where the name conflicts
"xblack" | "xterm_black" => Color::Fixed(0).normal(),
"maroon" | "xterm_maroon" => Color::Fixed(1).normal(),
"xgreen" | "xterm_green" => Color::Fixed(2).normal(),
"olive" | "xterm_olive" => Color::Fixed(3).normal(),
"navy" | "xterm_navy" => Color::Fixed(4).normal(),
"xpurplea" | "xterm_purplea" => Color::Fixed(5).normal(),
"teal" | "xterm_teal" => Color::Fixed(6).normal(),
"silver" | "xterm_silver" => Color::Fixed(7).normal(),
"grey" | "xterm_grey" => Color::Fixed(8).normal(),
"xred" | "xterm_red" => Color::Fixed(9).normal(),
"lime" | "xterm_lime" => Color::Fixed(10).normal(),
"xyellow" | "xterm_yellow" => Color::Fixed(11).normal(),
"xblue" | "xterm_blue" => Color::Fixed(12).normal(),
"fuchsia" | "xterm_fuchsia" => Color::Fixed(13).normal(),
"aqua" | "xterm_aqua" => Color::Fixed(14).normal(),
"xwhite" | "xterm_white" => Color::Fixed(15).normal(),
"grey0" | "xterm_grey0" => Color::Fixed(16).normal(),
"navyblue" | "xterm_navyblue" => Color::Fixed(17).normal(),
"darkblue" | "xterm_darkblue" => Color::Fixed(18).normal(),
"blue3a" | "xterm_blue3a" => Color::Fixed(19).normal(),
"blue3b" | "xterm_blue3b" => Color::Fixed(20).normal(),
"blue1" | "xterm_blue1" => Color::Fixed(21).normal(),
"darkgreen" | "xterm_darkgreen" => Color::Fixed(22).normal(),
"deepskyblue4a" | "xterm_deepskyblue4a" => Color::Fixed(23).normal(),
"deepskyblue4b" | "xterm_deepskyblue4b" => Color::Fixed(24).normal(),
"deepskyblue4c" | "xterm_deepskyblue4c" => Color::Fixed(25).normal(),
"dodgerblue3" | "xterm_dodgerblue3" => Color::Fixed(26).normal(),
"dodgerblue2" | "xterm_dodgerblue2" => Color::Fixed(27).normal(),
"green4" | "xterm_green4" => Color::Fixed(28).normal(),
"springgreen4" | "xterm_springgreen4" => Color::Fixed(29).normal(),
"turquoise4" | "xterm_turquoise4" => Color::Fixed(30).normal(),
"deepskyblue3a" | "xterm_deepskyblue3a" => Color::Fixed(31).normal(),
"deepskyblue3b" | "xterm_deepskyblue3b" => Color::Fixed(32).normal(),
"dodgerblue1" | "xterm_dodgerblue1" => Color::Fixed(33).normal(),
"green3a" | "xterm_green3a" => Color::Fixed(34).normal(),
"springgreen3a" | "xterm_springgreen3a" => Color::Fixed(35).normal(),
"darkcyan" | "xterm_darkcyan" => Color::Fixed(36).normal(),
"lightseagreen" | "xterm_lightseagreen" => Color::Fixed(37).normal(),
"deepskyblue2" | "xterm_deepskyblue2" => Color::Fixed(38).normal(),
"deepskyblue1" | "xterm_deepskyblue1" => Color::Fixed(39).normal(),
"green3b" | "xterm_green3b" => Color::Fixed(40).normal(),
"springgreen3b" | "xterm_springgreen3b" => Color::Fixed(41).normal(),
"springgreen2a" | "xterm_springgreen2a" => Color::Fixed(42).normal(),
"cyan3" | "xterm_cyan3" => Color::Fixed(43).normal(),
"darkturquoise" | "xterm_darkturquoise" => Color::Fixed(44).normal(),
"turquoise2" | "xterm_turquoise2" => Color::Fixed(45).normal(),
"green1" | "xterm_green1" => Color::Fixed(46).normal(),
"springgreen2b" | "xterm_springgreen2b" => Color::Fixed(47).normal(),
"springgreen1" | "xterm_springgreen1" => Color::Fixed(48).normal(),
"mediumspringgreen" | "xterm_mediumspringgreen" => Color::Fixed(49).normal(),
"cyan2" | "xterm_cyan2" => Color::Fixed(50).normal(),
"cyan1" | "xterm_cyan1" => Color::Fixed(51).normal(),
"darkreda" | "xterm_darkreda" => Color::Fixed(52).normal(),
"deeppink4a" | "xterm_deeppink4a" => Color::Fixed(53).normal(),
"purple4a" | "xterm_purple4a" => Color::Fixed(54).normal(),
"purple4b" | "xterm_purple4b" => Color::Fixed(55).normal(),
"purple3" | "xterm_purple3" => Color::Fixed(56).normal(),
"blueviolet" | "xterm_blueviolet" => Color::Fixed(57).normal(),
"orange4a" | "xterm_orange4a" => Color::Fixed(58).normal(),
"grey37" | "xterm_grey37" => Color::Fixed(59).normal(),
"mediumpurple4" | "xterm_mediumpurple4" => Color::Fixed(60).normal(),
"slateblue3a" | "xterm_slateblue3a" => Color::Fixed(61).normal(),
"slateblue3b" | "xterm_slateblue3b" => Color::Fixed(62).normal(),
"royalblue1" | "xterm_royalblue1" => Color::Fixed(63).normal(),
"chartreuse4" | "xterm_chartreuse4" => Color::Fixed(64).normal(),
"darkseagreen4a" | "xterm_darkseagreen4a" => Color::Fixed(65).normal(),
"paleturquoise4" | "xterm_paleturquoise4" => Color::Fixed(66).normal(),
"steelblue" | "xterm_steelblue" => Color::Fixed(67).normal(),
"steelblue3" | "xterm_steelblue3" => Color::Fixed(68).normal(),
"cornflowerblue" | "xterm_cornflowerblue" => Color::Fixed(69).normal(),
"chartreuse3a" | "xterm_chartreuse3a" => Color::Fixed(70).normal(),
"darkseagreen4b" | "xterm_darkseagreen4b" => Color::Fixed(71).normal(),
"cadetbluea" | "xterm_cadetbluea" => Color::Fixed(72).normal(),
"cadetblueb" | "xterm_cadetblueb" => Color::Fixed(73).normal(),
"skyblue3" | "xterm_skyblue3" => Color::Fixed(74).normal(),
"steelblue1a" | "xterm_steelblue1a" => Color::Fixed(75).normal(),
"chartreuse3b" | "xterm_chartreuse3b" => Color::Fixed(76).normal(),
"palegreen3a" | "xterm_palegreen3a" => Color::Fixed(77).normal(),
"seagreen3" | "xterm_seagreen3" => Color::Fixed(78).normal(),
"aquamarine3" | "xterm_aquamarine3" => Color::Fixed(79).normal(),
"mediumturquoise" | "xterm_mediumturquoise" => Color::Fixed(80).normal(),
"steelblue1b" | "xterm_steelblue1b" => Color::Fixed(81).normal(),
"chartreuse2a" | "xterm_chartreuse2a" => Color::Fixed(82).normal(),
"seagreen2" | "xterm_seagreen2" => Color::Fixed(83).normal(),
"seagreen1a" | "xterm_seagreen1a" => Color::Fixed(84).normal(),
"seagreen1b" | "xterm_seagreen1b" => Color::Fixed(85).normal(),
"aquamarine1a" | "xterm_aquamarine1a" => Color::Fixed(86).normal(),
"darkslategray2" | "xterm_darkslategray2" => Color::Fixed(87).normal(),
"darkredb" | "xterm_darkredb" => Color::Fixed(88).normal(),
"deeppink4b" | "xterm_deeppink4b" => Color::Fixed(89).normal(),
"darkmagentaa" | "xterm_darkmagentaa" => Color::Fixed(90).normal(),
"darkmagentab" | "xterm_darkmagentab" => Color::Fixed(91).normal(),
"darkvioleta" | "xterm_darkvioleta" => Color::Fixed(92).normal(),
"xpurpleb" | "xterm_purpleb" => Color::Fixed(93).normal(),
"orange4b" | "xterm_orange4b" => Color::Fixed(94).normal(),
"lightpink4" | "xterm_lightpink4" => Color::Fixed(95).normal(),
"plum4" | "xterm_plum4" => Color::Fixed(96).normal(),
"mediumpurple3a" | "xterm_mediumpurple3a" => Color::Fixed(97).normal(),
"mediumpurple3b" | "xterm_mediumpurple3b" => Color::Fixed(98).normal(),
"slateblue1" | "xterm_slateblue1" => Color::Fixed(99).normal(),
"yellow4a" | "xterm_yellow4a" => Color::Fixed(100).normal(),
"wheat4" | "xterm_wheat4" => Color::Fixed(101).normal(),
"grey53" | "xterm_grey53" => Color::Fixed(102).normal(),
"lightslategrey" | "xterm_lightslategrey" => Color::Fixed(103).normal(),
"mediumpurple" | "xterm_mediumpurple" => Color::Fixed(104).normal(),
"lightslateblue" | "xterm_lightslateblue" => Color::Fixed(105).normal(),
"yellow4b" | "xterm_yellow4b" => Color::Fixed(106).normal(),
"darkolivegreen3a" | "xterm_darkolivegreen3a" => Color::Fixed(107).normal(),
"darkseagreen" | "xterm_darkseagreen" => Color::Fixed(108).normal(),
"lightskyblue3a" | "xterm_lightskyblue3a" => Color::Fixed(109).normal(),
"lightskyblue3b" | "xterm_lightskyblue3b" => Color::Fixed(110).normal(),
"skyblue2" | "xterm_skyblue2" => Color::Fixed(111).normal(),
"chartreuse2b" | "xterm_chartreuse2b" => Color::Fixed(112).normal(),
"darkolivegreen3b" | "xterm_darkolivegreen3b" => Color::Fixed(113).normal(),
"palegreen3b" | "xterm_palegreen3b" => Color::Fixed(114).normal(),
"darkseagreen3a" | "xterm_darkseagreen3a" => Color::Fixed(115).normal(),
"darkslategray3" | "xterm_darkslategray3" => Color::Fixed(116).normal(),
"skyblue1" | "xterm_skyblue1" => Color::Fixed(117).normal(),
"chartreuse1" | "xterm_chartreuse1" => Color::Fixed(118).normal(),
"lightgreena" | "xterm_lightgreena" => Color::Fixed(119).normal(),
"lightgreenb" | "xterm_lightgreenb" => Color::Fixed(120).normal(),
"palegreen1a" | "xterm_palegreen1a" => Color::Fixed(121).normal(),
"aquamarine1b" | "xterm_aquamarine1b" => Color::Fixed(122).normal(),
"darkslategray1" | "xterm_darkslategray1" => Color::Fixed(123).normal(),
"red3a" | "xterm_red3a" => Color::Fixed(124).normal(),
"deeppink4c" | "xterm_deeppink4c" => Color::Fixed(125).normal(),
"mediumvioletred" | "xterm_mediumvioletred" => Color::Fixed(126).normal(),
"magenta3" | "xterm_magenta3" => Color::Fixed(127).normal(),
"darkvioletb" | "xterm_darkvioletb" => Color::Fixed(128).normal(),
"purplec" | "xterm_purplec" => Color::Fixed(129).normal(),
"darkorange3a" | "xterm_darkorange3a" => Color::Fixed(130).normal(),
"indianreda" | "xterm_indianreda" => Color::Fixed(131).normal(),
"hotpink3a" | "xterm_hotpink3a" => Color::Fixed(132).normal(),
"mediumorchid3" | "xterm_mediumorchid3" => Color::Fixed(133).normal(),
"mediumorchid" | "xterm_mediumorchid" => Color::Fixed(134).normal(),
"mediumpurple2a" | "xterm_mediumpurple2a" => Color::Fixed(135).normal(),
"darkgoldenrod" | "xterm_darkgoldenrod" => Color::Fixed(136).normal(),
"lightsalmon3a" | "xterm_lightsalmon3a" => Color::Fixed(137).normal(),
"rosybrown" | "xterm_rosybrown" => Color::Fixed(138).normal(),
"grey63" | "xterm_grey63" => Color::Fixed(139).normal(),
"mediumpurple2b" | "xterm_mediumpurple2b" => Color::Fixed(140).normal(),
"mediumpurple1" | "xterm_mediumpurple1" => Color::Fixed(141).normal(),
"gold3a" | "xterm_gold3a" => Color::Fixed(142).normal(),
"darkkhaki" | "xterm_darkkhaki" => Color::Fixed(143).normal(),
"navajowhite3" | "xterm_navajowhite3" => Color::Fixed(144).normal(),
"grey69" | "xterm_grey69" => Color::Fixed(145).normal(),
"lightsteelblue3" | "xterm_lightsteelblue3" => Color::Fixed(146).normal(),
"lightsteelblue" | "xterm_lightsteelblue" => Color::Fixed(147).normal(),
"yellow3a" | "xterm_yellow3a" => Color::Fixed(148).normal(),
"darkolivegreen3c" | "xterm_darkolivegreen3c" => Color::Fixed(149).normal(),
"darkseagreen3b" | "xterm_darkseagreen3b" => Color::Fixed(150).normal(),
"darkseagreen2a" | "xterm_darkseagreen2a" => Color::Fixed(151).normal(),
"lightcyan3" | "xterm_lightcyan3" => Color::Fixed(152).normal(),
"lightskyblue1" | "xterm_lightskyblue1" => Color::Fixed(153).normal(),
"greenyellow" | "xterm_greenyellow" => Color::Fixed(154).normal(),
"darkolivegreen2" | "xterm_darkolivegreen2" => Color::Fixed(155).normal(),
"palegreen1b" | "xterm_palegreen1b" => Color::Fixed(156).normal(),
"darkseagreen2b" | "xterm_darkseagreen2b" => Color::Fixed(157).normal(),
"darkseagreen1a" | "xterm_darkseagreen1a" => Color::Fixed(158).normal(),
"paleturquoise1" | "xterm_paleturquoise1" => Color::Fixed(159).normal(),
"red3b" | "xterm_red3b" => Color::Fixed(160).normal(),
"deeppink3a" | "xterm_deeppink3a" => Color::Fixed(161).normal(),
"deeppink3b" | "xterm_deeppink3b" => Color::Fixed(162).normal(),
"magenta3a" | "xterm_magenta3a" => Color::Fixed(163).normal(),
"magenta3b" | "xterm_magenta3b" => Color::Fixed(164).normal(),
"magenta2a" | "xterm_magenta2a" => Color::Fixed(165).normal(),
"darkorange3b" | "xterm_darkorange3b" => Color::Fixed(166).normal(),
"indianredb" | "xterm_indianredb" => Color::Fixed(167).normal(),
"hotpink3b" | "xterm_hotpink3b" => Color::Fixed(168).normal(),
"hotpink2" | "xterm_hotpink2" => Color::Fixed(169).normal(),
"orchid" | "xterm_orchid" => Color::Fixed(170).normal(),
"mediumorchid1a" | "xterm_mediumorchid1a" => Color::Fixed(171).normal(),
"orange3" | "xterm_orange3" => Color::Fixed(172).normal(),
"lightsalmon3b" | "xterm_lightsalmon3b" => Color::Fixed(173).normal(),
"lightpink3" | "xterm_lightpink3" => Color::Fixed(174).normal(),
"pink3" | "xterm_pink3" => Color::Fixed(175).normal(),
"plum3" | "xterm_plum3" => Color::Fixed(176).normal(),
"violet" | "xterm_violet" => Color::Fixed(177).normal(),
"gold3b" | "xterm_gold3b" => Color::Fixed(178).normal(),
"lightgoldenrod3" | "xterm_lightgoldenrod3" => Color::Fixed(179).normal(),
"tan" | "xterm_tan" => Color::Fixed(180).normal(),
"mistyrose3" | "xterm_mistyrose3" => Color::Fixed(181).normal(),
"thistle3" | "xterm_thistle3" => Color::Fixed(182).normal(),
"plum2" | "xterm_plum2" => Color::Fixed(183).normal(),
"yellow3b" | "xterm_yellow3b" => Color::Fixed(184).normal(),
"khaki3" | "xterm_khaki3" => Color::Fixed(185).normal(),
"lightgoldenrod2" | "xterm_lightgoldenrod2" => Color::Fixed(186).normal(),
"lightyellow3" | "xterm_lightyellow3" => Color::Fixed(187).normal(),
"grey84" | "xterm_grey84" => Color::Fixed(188).normal(),
"lightsteelblue1" | "xterm_lightsteelblue1" => Color::Fixed(189).normal(),
"yellow2" | "xterm_yellow2" => Color::Fixed(190).normal(),
"darkolivegreen1a" | "xterm_darkolivegreen1a" => Color::Fixed(191).normal(),
"darkolivegreen1b" | "xterm_darkolivegreen1b" => Color::Fixed(192).normal(),
"darkseagreen1b" | "xterm_darkseagreen1b" => Color::Fixed(193).normal(),
"honeydew2" | "xterm_honeydew2" => Color::Fixed(194).normal(),
"lightcyan1" | "xterm_lightcyan1" => Color::Fixed(195).normal(),
"red1" | "xterm_red1" => Color::Fixed(196).normal(),
"deeppink2" | "xterm_deeppink2" => Color::Fixed(197).normal(),
"deeppink1a" | "xterm_deeppink1a" => Color::Fixed(198).normal(),
"deeppink1b" | "xterm_deeppink1b" => Color::Fixed(199).normal(),
"magenta2b" | "xterm_magenta2b" => Color::Fixed(200).normal(),
"magenta1" | "xterm_magenta1" => Color::Fixed(201).normal(),
"orangered1" | "xterm_orangered1" => Color::Fixed(202).normal(),
"indianred1a" | "xterm_indianred1a" => Color::Fixed(203).normal(),
"indianred1b" | "xterm_indianred1b" => Color::Fixed(204).normal(),
"hotpinka" | "xterm_hotpinka" => Color::Fixed(205).normal(),
"hotpinkb" | "xterm_hotpinkb" => Color::Fixed(206).normal(),
"mediumorchid1b" | "xterm_mediumorchid1b" => Color::Fixed(207).normal(),
"darkorange" | "xterm_darkorange" => Color::Fixed(208).normal(),
"salmon1" | "xterm_salmon1" => Color::Fixed(209).normal(),
"lightcoral" | "xterm_lightcoral" => Color::Fixed(210).normal(),
"palevioletred1" | "xterm_palevioletred1" => Color::Fixed(211).normal(),
"orchid2" | "xterm_orchid2" => Color::Fixed(212).normal(),
"orchid1" | "xterm_orchid1" => Color::Fixed(213).normal(),
"orange1" | "xterm_orange1" => Color::Fixed(214).normal(),
"sandybrown" | "xterm_sandybrown" => Color::Fixed(215).normal(),
"lightsalmon1" | "xterm_lightsalmon1" => Color::Fixed(216).normal(),
"lightpink1" | "xterm_lightpink1" => Color::Fixed(217).normal(),
"pink1" | "xterm_pink1" => Color::Fixed(218).normal(),
"plum1" | "xterm_plum1" => Color::Fixed(219).normal(),
"gold1" | "xterm_gold1" => Color::Fixed(220).normal(),
"lightgoldenrod2a" | "xterm_lightgoldenrod2a" => Color::Fixed(221).normal(),
"lightgoldenrod2b" | "xterm_lightgoldenrod2b" => Color::Fixed(222).normal(),
"navajowhite1" | "xterm_navajowhite1" => Color::Fixed(223).normal(),
"mistyrose1" | "xterm_mistyrose1" => Color::Fixed(224).normal(),
"thistle1" | "xterm_thistle1" => Color::Fixed(225).normal(),
"yellow1" | "xterm_yellow1" => Color::Fixed(226).normal(),
"lightgoldenrod1" | "xterm_lightgoldenrod1" => Color::Fixed(227).normal(),
"khaki1" | "xterm_khaki1" => Color::Fixed(228).normal(),
"wheat1" | "xterm_wheat1" => Color::Fixed(229).normal(),
"cornsilk1" | "xterm_cornsilk1" => Color::Fixed(230).normal(),
"grey100" | "xterm_grey100" => Color::Fixed(231).normal(),
"grey3" | "xterm_grey3" => Color::Fixed(232).normal(),
"grey7" | "xterm_grey7" => Color::Fixed(233).normal(),
"grey11" | "xterm_grey11" => Color::Fixed(234).normal(),
"grey15" | "xterm_grey15" => Color::Fixed(235).normal(),
"grey19" | "xterm_grey19" => Color::Fixed(236).normal(),
"grey23" | "xterm_grey23" => Color::Fixed(237).normal(),
"grey27" | "xterm_grey27" => Color::Fixed(238).normal(),
"grey30" | "xterm_grey30" => Color::Fixed(239).normal(),
"grey35" | "xterm_grey35" => Color::Fixed(240).normal(),
"grey39" | "xterm_grey39" => Color::Fixed(241).normal(),
"grey42" | "xterm_grey42" => Color::Fixed(242).normal(),
"grey46" | "xterm_grey46" => Color::Fixed(243).normal(),
"grey50" | "xterm_grey50" => Color::Fixed(244).normal(),
"grey54" | "xterm_grey54" => Color::Fixed(245).normal(),
"grey58" | "xterm_grey58" => Color::Fixed(246).normal(),
"grey62" | "xterm_grey62" => Color::Fixed(247).normal(),
"grey66" | "xterm_grey66" => Color::Fixed(248).normal(),
"grey70" | "xterm_grey70" => Color::Fixed(249).normal(),
"grey74" | "xterm_grey74" => Color::Fixed(250).normal(),
"grey78" | "xterm_grey78" => Color::Fixed(251).normal(),
"grey82" | "xterm_grey82" => Color::Fixed(252).normal(),
"grey85" | "xterm_grey85" => Color::Fixed(253).normal(),
"grey89" | "xterm_grey89" => Color::Fixed(254).normal(),
"grey93" | "xterm_grey93" => Color::Fixed(255).normal(),
_ => Color::White.normal(),
}
}
pub fn lookup_color(s: &str) -> Option<Color> {
let color = match s {
"g" | "green" => Color::Green,
"lg" | "light_green" => Color::LightGreen,
"r" | "red" => Color::Red,
"lr" | "light_red" => Color::LightRed,
"u" | "blue" => Color::Blue,
"lu" | "light_blue" => Color::LightBlue,
"b" | "black" => Color::Black,
"ligr" | "light_gray" => Color::LightGray,
"y" | "yellow" => Color::Yellow,
"ly" | "light_yellow" => Color::LightYellow,
"p" | "purple" => Color::Purple,
"lp" | "light_purple" => Color::LightPurple,
"c" | "cyan" => Color::Cyan,
"lc" | "light_cyan" => Color::LightCyan,
"w" | "white" => Color::White,
"dgr" | "dark_gray" => Color::DarkGray,
"def" | "default" => Color::Default,
_ => return None,
};
Some(color)
}
fn fill_modifiers(attrs: &str, style: &mut Style) {
// setup the attributes available in nu_ansi_term::Style
//
// since we can combine styles like bold-italic, iterate through the chars
// and set the bools for later use in the nu_ansi_term::Style application
for ch in attrs.to_lowercase().chars() {
match ch {
'l' => style.is_blink = true,
'b' => style.is_bold = true,
'd' => style.is_dimmed = true,
'h' => style.is_hidden = true,
'i' => style.is_italic = true,
'r' => style.is_reverse = true,
's' => style.is_strikethrough = true,
'u' => style.is_underline = true,
'n' => (),
_ => (),
}
}
}
fn lookup_color_str(s: &str) -> Option<Color> {
if s.starts_with('#') {
color_from_hex(s).ok().and_then(|c| c)
} else {
lookup_color(s)
}
}

View File

@ -1,56 +1,45 @@
use crate::{color_config::lookup_ansi_color_style, color_record_to_nustyle};
use crate::color_config::lookup_ansi_color_style;
use nu_ansi_term::{Color, Style};
use nu_protocol::{Config, Value};
// The default colors for shapes, used when there is no config for them.
pub fn default_shape_color(shape: String) -> Style {
match shape.as_ref() {
"shape_and" => Style::new().fg(Color::Purple).bold(),
"shape_binary" => Style::new().fg(Color::Purple).bold(),
"shape_block" => Style::new().fg(Color::Blue).bold(),
"shape_bool" => Style::new().fg(Color::LightCyan),
"shape_custom" => Style::new().fg(Color::Green),
"shape_datetime" => Style::new().fg(Color::Cyan).bold(),
"shape_directory" => Style::new().fg(Color::Cyan),
"shape_external" => Style::new().fg(Color::Cyan),
"shape_externalarg" => Style::new().fg(Color::Green).bold(),
"shape_filepath" => Style::new().fg(Color::Cyan),
"shape_flag" => Style::new().fg(Color::Blue).bold(),
"shape_float" => Style::new().fg(Color::Purple).bold(),
"shape_garbage" => Style::new().fg(Color::White).on(Color::Red).bold(),
"shape_globpattern" => Style::new().fg(Color::Cyan).bold(),
"shape_int" => Style::new().fg(Color::Purple).bold(),
"shape_internalcall" => Style::new().fg(Color::Cyan).bold(),
"shape_list" => Style::new().fg(Color::Cyan).bold(),
"shape_literal" => Style::new().fg(Color::Blue),
"shape_nothing" => Style::new().fg(Color::LightCyan),
"shape_operator" => Style::new().fg(Color::Yellow),
"shape_or" => Style::new().fg(Color::Purple).bold(),
"shape_pipe" => Style::new().fg(Color::Purple).bold(),
"shape_range" => Style::new().fg(Color::Yellow).bold(),
"shape_record" => Style::new().fg(Color::Cyan).bold(),
"shape_redirection" => Style::new().fg(Color::Purple).bold(),
"shape_signature" => Style::new().fg(Color::Green).bold(),
"shape_string" => Style::new().fg(Color::Green),
"shape_string_interpolation" => Style::new().fg(Color::Cyan).bold(),
"shape_table" => Style::new().fg(Color::Blue).bold(),
"shape_variable" => Style::new().fg(Color::Purple),
_ => Style::default(),
}
}
use nu_protocol::Config;
pub fn get_shape_color(shape: String, conf: &Config) -> Style {
match conf.color_config.get(shape.as_str()) {
Some(int_color) => {
// Shapes do not use color_config closures, currently.
match int_color {
Value::Record { .. } => color_record_to_nustyle(int_color),
Value::String { val, .. } => lookup_ansi_color_style(val),
// Defer to the default in the event of incorrect types being given
// (i.e. treat null, etc. as the value being unset)
_ => default_shape_color(shape),
}
}
None => default_shape_color(shape),
Some(int_color) => match int_color.as_string() {
Ok(int_color) => lookup_ansi_color_style(&int_color),
Err(_) => Style::default(),
},
None => match shape.as_ref() {
"shape_garbage" => Style::new().fg(Color::White).on(Color::Red).bold(),
"shape_binary" => Style::new().fg(Color::Purple).bold(),
"shape_bool" => Style::new().fg(Color::LightCyan),
"shape_int" => Style::new().fg(Color::Purple).bold(),
"shape_float" => Style::new().fg(Color::Purple).bold(),
"shape_range" => Style::new().fg(Color::Yellow).bold(),
"shape_internalcall" => Style::new().fg(Color::Cyan).bold(),
"shape_external" => Style::new().fg(Color::Cyan),
"shape_externalarg" => Style::new().fg(Color::Green).bold(),
"shape_literal" => Style::new().fg(Color::Blue),
"shape_operator" => Style::new().fg(Color::Yellow),
"shape_signature" => Style::new().fg(Color::Green).bold(),
"shape_string" => Style::new().fg(Color::Green),
"shape_string_interpolation" => Style::new().fg(Color::Cyan).bold(),
"shape_datetime" => Style::new().fg(Color::Cyan).bold(),
"shape_list" => Style::new().fg(Color::Cyan).bold(),
"shape_table" => Style::new().fg(Color::Blue).bold(),
"shape_record" => Style::new().fg(Color::Cyan).bold(),
"shape_block" => Style::new().fg(Color::Blue).bold(),
"shape_filepath" => Style::new().fg(Color::Cyan),
"shape_directory" => Style::new().fg(Color::Cyan),
"shape_globpattern" => Style::new().fg(Color::Cyan).bold(),
"shape_variable" => Style::new().fg(Color::Purple),
"shape_flag" => Style::new().fg(Color::Blue).bold(),
"shape_custom" => Style::new().fg(Color::Green),
"shape_pipe" => Style::new().fg(Color::Purple).bold(),
"shape_redirection" => Style::new().fg(Color::Purple).bold(),
"shape_and" => Style::new().fg(Color::Purple).bold(),
"shape_or" => Style::new().fg(Color::Purple).bold(),
"shape_nothing" => Style::new().fg(Color::LightCyan),
_ => Style::default(),
},
}
}

View File

@ -1,285 +0,0 @@
use crate::{color_record_to_nustyle, lookup_ansi_color_style, TextStyle};
use nu_ansi_term::{Color, Style};
use nu_engine::eval_block;
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
CliError, IntoPipelineData, Value,
};
use tabled::alignment::AlignmentHorizontal;
use std::{
collections::HashMap,
fmt::{Debug, Formatter, Result},
};
// ComputableStyle represents the valid user style types: a single color value, or a closure which
// takes an input value and produces a color value. The latter represents a value which
// is computed at use-time.
#[derive(Debug, Clone)]
pub enum ComputableStyle {
Static(Style),
Closure(Value),
}
// macro used for adding initial values to the style hashmap
macro_rules! initial {
($a:expr, $b:expr) => {
($a.to_string(), ComputableStyle::Static($b))
};
}
// An alias for the mapping used internally by StyleComputer.
pub type StyleMapping = HashMap<String, ComputableStyle>;
//
// A StyleComputer is an all-in-one way to compute styles. A nu command can
// simply create it with from_config(), and then use it with compute().
// It stores the engine state and stack needed to run closures that
// may be defined as a user style.
//
pub struct StyleComputer<'a> {
engine_state: &'a EngineState,
stack: &'a Stack,
map: StyleMapping,
}
impl<'a> StyleComputer<'a> {
// This is NOT meant to be used in most cases - please use from_config() instead.
// This only exists for testing purposes.
pub fn new(
engine_state: &'a EngineState,
stack: &'a Stack,
map: StyleMapping,
) -> StyleComputer<'a> {
StyleComputer {
engine_state,
stack,
map,
}
}
// The main method. Takes a string name which maps to a color_config style name,
// and a Nu value to pipe into any closures that may have been defined there.
pub fn compute(&self, style_name: &str, value: &Value) -> Style {
match self.map.get(style_name) {
// Static values require no computation.
Some(ComputableStyle::Static(s)) => *s,
// Closures are run here.
Some(ComputableStyle::Closure(Value::Closure {
val: block_id,
captures,
span,
})) => {
let block = self.engine_state.get_block(*block_id).clone();
// Because captures_to_stack() clones, we don't need to use with_env() here
// (contrast with_env() usage in `each` or `do`).
let mut stack = self.stack.captures_to_stack(captures);
// Support 1-argument blocks as well as 0-argument blocks.
if let Some(var) = block.signature.get_positional(0) {
if let Some(var_id) = &var.var_id {
stack.add_var(*var_id, value.clone());
}
}
// Run the block.
match eval_block(
self.engine_state,
&mut stack,
&block,
value.clone().into_pipeline_data(),
false,
false,
) {
Ok(v) => {
let value = v.into_value(*span);
// These should be the same color data forms supported by color_config.
match value {
Value::Record { .. } => color_record_to_nustyle(&value),
Value::String { val, .. } => lookup_ansi_color_style(&val),
_ => Style::default(),
}
}
// This is basically a copy of nu_cli::report_error(), but that isn't usable due to
// dependencies. While crudely spitting out a bunch of errors like this is not ideal,
// currently hook closure errors behave roughly the same.
Err(e) => {
eprintln!(
"Error: {:?}",
CliError(&e, &StateWorkingSet::new(self.engine_state))
);
Style::default()
}
}
}
// There should be no other kinds of values (due to create_map() in config.rs filtering them out)
// so this is just a fallback.
_ => Style::default(),
}
}
// Used only by the `table` command.
pub fn style_primitive(&self, value: &Value) -> TextStyle {
let s = self.compute(&value.get_type().to_string(), value);
match *value {
Value::Bool { .. } => TextStyle::with_style(AlignmentHorizontal::Left, s),
Value::Int { .. } => TextStyle::with_style(AlignmentHorizontal::Right, s),
Value::Filesize { .. } => TextStyle::with_style(AlignmentHorizontal::Right, s),
Value::Duration { .. } => TextStyle::with_style(AlignmentHorizontal::Right, s),
Value::Date { .. } => TextStyle::with_style(AlignmentHorizontal::Left, s),
Value::Range { .. } => TextStyle::with_style(AlignmentHorizontal::Left, s),
Value::Float { .. } => TextStyle::with_style(AlignmentHorizontal::Right, s),
Value::String { .. } => TextStyle::with_style(AlignmentHorizontal::Left, s),
Value::Nothing { .. } => TextStyle::with_style(AlignmentHorizontal::Left, s),
Value::Binary { .. } => TextStyle::with_style(AlignmentHorizontal::Left, s),
Value::CellPath { .. } => TextStyle::with_style(AlignmentHorizontal::Left, s),
Value::Record { .. } | Value::List { .. } | Value::Block { .. } => {
TextStyle::with_style(AlignmentHorizontal::Left, s)
}
_ => TextStyle::basic_left(),
}
}
// The main constructor.
pub fn from_config(engine_state: &'a EngineState, stack: &'a Stack) -> StyleComputer<'a> {
let config = engine_state.get_config();
// Create the hashmap
let mut map: StyleMapping = HashMap::from([
initial!("separator", Color::White.normal()),
initial!(
"leading_trailing_space_bg",
Style::default().on(Color::Rgb(128, 128, 128))
),
initial!("header", Color::White.normal()),
initial!("empty", Color::White.normal()),
initial!("bool", Color::White.normal()),
initial!("int", Color::White.normal()),
initial!("filesize", Color::White.normal()),
initial!("duration", Color::White.normal()),
initial!("date", Color::White.normal()),
initial!("range", Color::White.normal()),
initial!("float", Color::White.normal()),
initial!("string", Color::White.normal()),
initial!("nothing", Color::White.normal()),
initial!("binary", Color::White.normal()),
initial!("cellpath", Color::White.normal()),
initial!("row_index", Color::Green.bold()),
initial!("record", Color::White.normal()),
initial!("list", Color::White.normal()),
initial!("block", Color::White.normal()),
initial!("hints", Color::DarkGray.normal()),
]);
for (key, value) in &config.color_config {
match value {
Value::Closure { .. } => {
map.insert(key.to_string(), ComputableStyle::Closure(value.clone()));
}
Value::Record { .. } => {
map.insert(
key.to_string(),
ComputableStyle::Static(color_record_to_nustyle(value)),
);
}
Value::String { val, .. } => {
// update the stylemap with the found key
let color = lookup_ansi_color_style(val.as_str());
if let Some(v) = map.get_mut(key) {
*v = ComputableStyle::Static(color);
} else {
map.insert(key.to_string(), ComputableStyle::Static(color));
}
}
// This should never occur.
_ => (),
}
}
StyleComputer::new(engine_state, stack, map)
}
}
// Because EngineState doesn't have Debug (Dec 2022),
// this incomplete representation must be used.
impl<'a> Debug for StyleComputer<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_struct("StyleComputer")
.field("map", &self.map)
.finish()
}
}
#[test]
fn test_computable_style_static() {
use nu_protocol::Span;
let style1 = Style::default().italic();
let style2 = Style::default().underline();
// Create a "dummy" style_computer for this test.
let dummy_engine_state = EngineState::new();
let mut dummy_stack = Stack::new();
let style_computer = StyleComputer::new(
&dummy_engine_state,
&mut dummy_stack,
HashMap::from([
("string".into(), ComputableStyle::Static(style1)),
("row_index".into(), ComputableStyle::Static(style2)),
]),
);
assert_eq!(
style_computer.compute("string", &Value::nothing(Span::unknown())),
style1
);
assert_eq!(
style_computer.compute("row_index", &Value::nothing(Span::unknown())),
style2
);
}
// Because each closure currently runs in a separate environment, checks that the closures have run
// must use the filesystem.
#[test]
fn test_computable_style_closure_basic() {
use nu_test_support::{nu, nu_repl_code, playground::Playground};
Playground::setup("computable_style_closure_basic", |dirs, _| {
let inp = [
r#"let-env config = {
color_config: {
string: {|e| touch ($e + '.obj'); 'red' }
}
};"#,
"[bell book candle] | table | ignore",
"ls | get name | to nuon",
];
let actual_repl = nu!(cwd: dirs.test(), nu_repl_code(&inp));
assert_eq!(actual_repl.err, "");
assert_eq!(actual_repl.out, "[bell.obj, book.obj, candle.obj]");
});
}
#[test]
fn test_computable_style_closure_errors() {
use nu_test_support::{nu, nu_repl_code};
let inp = [
r#"let-env config = {
color_config: {
string: {|e| $e + 2 }
}
};"#,
"[bell] | table",
];
let actual_repl = nu!(cwd: ".", nu_repl_code(&inp));
// Check that the error was printed
assert!(actual_repl.err.contains("type mismatch for operator"));
// Check that the value was printed
assert!(actual_repl.out.contains("bell"));
}

View File

@ -5,35 +5,33 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-command"
edition = "2021"
license = "MIT"
name = "nu-command"
version = "0.74.0"
version = "0.72.1"
build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-color-config = { path = "../nu-color-config", version = "0.74.0" }
nu-engine = { path = "../nu-engine", version = "0.74.0" }
nu-glob = { path = "../nu-glob", version = "0.74.0" }
nu-json = { path = "../nu-json", version = "0.74.0" }
nu-parser = { path = "../nu-parser", version = "0.74.0" }
nu-path = { path = "../nu-path", version = "0.74.0" }
nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.74.0" }
nu-protocol = { path = "../nu-protocol", version = "0.74.0" }
nu-system = { path = "../nu-system", version = "0.74.0" }
nu-table = { path = "../nu-table", version = "0.74.0" }
nu-term-grid = { path = "../nu-term-grid", version = "0.74.0" }
nu-utils = { path = "../nu-utils", version = "0.74.0" }
nu-explore = { path = "../nu-explore", version = "0.74.0" }
nu-color-config = { path = "../nu-color-config", version = "0.72.1" }
nu-engine = { path = "../nu-engine", version = "0.72.1" }
nu-glob = { path = "../nu-glob", version = "0.72.1" }
nu-json = { path = "../nu-json", version = "0.72.1" }
nu-parser = { path = "../nu-parser", version = "0.72.1" }
nu-path = { path = "../nu-path", version = "0.72.1" }
nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.72.1" }
nu-protocol = { path = "../nu-protocol", version = "0.72.1" }
nu-system = { path = "../nu-system", version = "0.72.1" }
nu-table = { path = "../nu-table", version = "0.72.1" }
nu-term-grid = { path = "../nu-term-grid", version = "0.72.1" }
nu-utils = { path = "../nu-utils", version = "0.72.1" }
nu-ansi-term = "0.46.0"
num-format = { version = "0.4.3" }
# Potential dependencies for extras
alphanumeric-sort = "1.4.4"
atty = "0.2.14"
base64 = "0.13.0"
byteorder = "1.4.3"
bytesize = "1.1.0"
calamine = "0.19.1"
calamine = "0.18.0"
chrono = { version = "0.4.23", features = ["unstable-locales", "std"], default-features = false }
chrono-humanize = "0.2.1"
chrono-tz = "0.6.3"
@ -54,24 +52,23 @@ indexmap = { version="1.7", features=["serde-1"] }
Inflector = "0.11"
is-root = "0.1.2"
itertools = "0.10.0"
lazy_static = "1.4.0"
log = "0.4.14"
lscolors = { version = "0.12.0", features = ["crossterm"], default-features = false }
md5 = { package = "md-5", version = "0.10.0" }
meval = "0.2.0"
mime = "0.3.16"
mime_guess = "2.0.4"
notify = "4.0.17"
num = { version = "0.4.0", optional = true }
num-traits = "0.2.14"
once_cell = "1.0"
open = "3.2.0"
pathdiff = "0.2.1"
powierza-coefficient = "1.0.2"
quick-xml = "0.25"
powierza-coefficient = "1.0.1"
quick-xml = "0.23.0"
rand = "0.8"
rayon = "1.5.1"
regex = "1.6.0"
reqwest = {version = "0.11", features = ["blocking", "json"] }
roxmltree = "0.16.0"
roxmltree = "0.14.0"
rust-embed = "6.3.0"
same-file = "1.0.6"
serde = { version="1.0.123", features=["derive"] }
@ -88,7 +85,6 @@ titlecase = "2.0.0"
toml = "0.5.8"
unicode-segmentation = "1.8.0"
url = "2.2.1"
percent-encoding = "2.2.0"
uuid = { version = "1.1.2", features = ["v4"] }
which = { version = "4.3.0", optional = true }
reedline = { version = "0.14.0", features = ["bashisms", "sqlite"]}
@ -158,7 +154,7 @@ sqlite = ["rusqlite"] # TODO: given that rusqlite is included in reedline, shoul
shadow-rs = { version = "0.16.1", default-features = false }
[dev-dependencies]
nu-test-support = { path = "../nu-test-support", version = "0.74.0" }
nu-test-support = { path = "../nu-test-support", version = "0.72.1" }
hamcrest2 = "0.3.0"
dirs-next = "2.0.0"

View File

@ -43,10 +43,6 @@ impl Command for SubCommand {
let head = call.head;
let target: i64 = call.req(engine_state, stack, 0)?;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty(head));
}
input.map(
move |value| operate(value, target, head),
engine_state.ctrlc.clone(),
@ -58,7 +54,10 @@ impl Command for SubCommand {
Example {
description: "Apply bits and to two numbers",
example: "2 | bits and 2",
result: Some(Value::test_int(2)),
result: Some(Value::Int {
val: 2,
span: Span::test_data(),
}),
},
Example {
description: "Apply logical and to a list of numbers",
@ -78,15 +77,13 @@ fn operate(value: Value, target: i64, head: Span) -> Value {
val: val & target,
span,
},
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => value,
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
head,
// This line requires the Value::Error match above.
other.expect_span(),
error: ShellError::UnsupportedInput(
format!(
"Only integer values are supported, input type: {:?}",
other.get_type()
),
other.span().unwrap_or(head),
),
},
}

View File

@ -2,7 +2,7 @@ use nu_engine::get_full_help;
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
Category, IntoPipelineData, PipelineData, Signature, Type, Value,
Category, IntoPipelineData, PipelineData, Signature, Value,
};
#[derive(Clone)]
@ -14,19 +14,13 @@ impl Command for Bits {
}
fn signature(&self) -> Signature {
Signature::build("bits")
.category(Category::Bits)
.input_output_types(vec![(Type::Nothing, Type::String)])
Signature::build("bits").category(Category::Bits)
}
fn usage(&self) -> &str {
"Various commands for working with bits"
}
fn extra_usage(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
@ -47,3 +41,15 @@ impl Command for Bits {
.into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use crate::Bits;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Bits {})
}
}

View File

@ -56,17 +56,11 @@ impl Command for SubCommand {
if let Some(val) = number_bytes {
return Err(ShellError::UnsupportedInput(
"Only 1, 2, 4, 8, or 'auto' bytes are supported as word sizes".to_string(),
"value originates from here".to_string(),
head,
val.span,
));
}
}
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty(head));
}
input.map(
move |value| operate(value, head, signed, bytes_len),
engine_state.ctrlc.clone(),
@ -146,17 +140,14 @@ fn operate(value: Value, head: Span, signed: bool, number_size: NumberBytes) ->
Value::Int { val: out_val, span }
}
}
other => match other {
// Propagate errors inside the value
Value::Error { .. } => other,
_ => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"numeric".into(),
other.get_type().to_string(),
head,
other.expect_span(),
other => Value::Error {
error: ShellError::UnsupportedInput(
format!(
"Only numerical values are supported, input type: {:?}",
other.get_type()
),
},
other.span().unwrap_or(head),
),
},
}
}

View File

@ -43,10 +43,6 @@ impl Command for SubCommand {
let head = call.head;
let target: i64 = call.req(engine_state, stack, 0)?;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty(head));
}
input.map(
move |value| operate(value, target, head),
engine_state.ctrlc.clone(),
@ -58,7 +54,10 @@ impl Command for SubCommand {
Example {
description: "Apply bits or to two numbers",
example: "2 | bits or 6",
result: Some(Value::test_int(6)),
result: Some(Value::Int {
val: 6,
span: Span::test_data(),
}),
},
Example {
description: "Apply logical or to a list of numbers",
@ -78,15 +77,13 @@ fn operate(value: Value, target: i64, head: Span) -> Value {
val: val | target,
span,
},
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => value,
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
head,
// This line requires the Value::Error match above.
other.expect_span(),
error: ShellError::UnsupportedInput(
format!(
"Only integer values are supported, input type: {:?}",
other.get_type()
),
other.span().unwrap_or(head),
),
},
}

View File

@ -60,16 +60,11 @@ impl Command for SubCommand {
if let Some(val) = number_bytes {
return Err(ShellError::UnsupportedInput(
"Only 1, 2, 4, 8, or 'auto' bytes are supported as word sizes".to_string(),
"value originates from here".to_string(),
head,
val.span,
));
}
}
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty(head));
}
input.map(
move |value| operate(value, bits, head, signed, bytes_len),
engine_state.ctrlc.clone(),
@ -81,7 +76,10 @@ impl Command for SubCommand {
Example {
description: "Rotate left a number with 2 bits",
example: "17 | bits rol 2",
result: Some(Value::test_int(68)),
result: Some(Value::Int {
val: 68,
span: Span::test_data(),
}),
},
Example {
description: "Rotate left a list of numbers with 2 bits",
@ -135,15 +133,13 @@ fn operate(value: Value, bits: usize, head: Span, signed: bool, number_size: Num
SignedEight => get_rotate_left(val as i64, bits, span),
}
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => value,
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
head,
// This line requires the Value::Error match above.
other.expect_span(),
error: ShellError::UnsupportedInput(
format!(
"Only integer values are supported, input type: {:?}",
other.get_type()
),
other.span().unwrap_or(head),
),
},
}

View File

@ -60,16 +60,11 @@ impl Command for SubCommand {
if let Some(val) = number_bytes {
return Err(ShellError::UnsupportedInput(
"Only 1, 2, 4, 8, or 'auto' bytes are supported as word sizes".to_string(),
"value originates from here".to_string(),
head,
val.span,
));
}
}
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty(head));
}
input.map(
move |value| operate(value, bits, head, signed, bytes_len),
engine_state.ctrlc.clone(),
@ -81,7 +76,10 @@ impl Command for SubCommand {
Example {
description: "Rotate right a number with 60 bits",
example: "17 | bits ror 60",
result: Some(Value::test_int(272)),
result: Some(Value::Int {
val: 272,
span: Span::test_data(),
}),
},
Example {
description: "Rotate right a list of numbers of one byte",
@ -139,15 +137,13 @@ fn operate(value: Value, bits: usize, head: Span, signed: bool, number_size: Num
SignedEight => get_rotate_right(val as i64, bits, span),
}
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => value,
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
head,
// This line requires the Value::Error match above.
other.expect_span(),
error: ShellError::UnsupportedInput(
format!(
"Only integer values are supported, input type: {:?}",
other.get_type()
),
other.span().unwrap_or(head),
),
},
}

View File

@ -60,16 +60,11 @@ impl Command for SubCommand {
if let Some(val) = number_bytes {
return Err(ShellError::UnsupportedInput(
"Only 1, 2, 4, 8, or 'auto' bytes are supported as word sizes".to_string(),
"value originates from here".to_string(),
head,
val.span,
));
}
}
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty(head));
}
input.map(
move |value| operate(value, bits, head, signed, bytes_len),
engine_state.ctrlc.clone(),
@ -81,17 +76,26 @@ impl Command for SubCommand {
Example {
description: "Shift left a number by 7 bits",
example: "2 | bits shl 7",
result: Some(Value::test_int(256)),
result: Some(Value::Int {
val: 256,
span: Span::test_data(),
}),
},
Example {
description: "Shift left a number with 1 byte by 7 bits",
example: "2 | bits shl 7 -n 1",
result: Some(Value::test_int(0)),
result: Some(Value::Int {
val: 0,
span: Span::test_data(),
}),
},
Example {
description: "Shift left a signed number by 1 bit",
example: "0x7F | bits shl 1 -s",
result: Some(Value::test_int(254)),
result: Some(Value::Int {
val: 254,
span: Span::test_data(),
}),
},
Example {
description: "Shift left a list of numbers",
@ -161,15 +165,13 @@ fn operate(value: Value, bits: usize, head: Span, signed: bool, number_size: Num
SignedEight => get_shift_left(val as i64, bits, span),
}
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => value,
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
head,
// This line requires the Value::Error match above.
other.expect_span(),
error: ShellError::UnsupportedInput(
format!(
"Only integer values are supported, input type: {:?}",
other.get_type()
),
other.span().unwrap_or(head),
),
},
}

View File

@ -60,16 +60,11 @@ impl Command for SubCommand {
if let Some(val) = number_bytes {
return Err(ShellError::UnsupportedInput(
"Only 1, 2, 4, 8, or 'auto' bytes are supported as word sizes".to_string(),
"value originates from here".to_string(),
head,
val.span,
));
}
}
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty(head));
}
input.map(
move |value| operate(value, bits, head, signed, bytes_len),
engine_state.ctrlc.clone(),
@ -81,7 +76,10 @@ impl Command for SubCommand {
Example {
description: "Shift right a number with 2 bits",
example: "8 | bits shr 2",
result: Some(Value::test_int(2)),
result: Some(Value::Int {
val: 2,
span: Span::test_data(),
}),
},
Example {
description: "Shift right a list of numbers",
@ -151,15 +149,13 @@ fn operate(value: Value, bits: usize, head: Span, signed: bool, number_size: Num
SignedEight => get_shift_right(val as i64, bits, span),
}
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => value,
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
head,
// This line requires the Value::Error match above.
other.expect_span(),
error: ShellError::UnsupportedInput(
format!(
"Only integer values are supported, input type: {:?}",
other.get_type()
),
other.span().unwrap_or(head),
),
},
}

View File

@ -42,10 +42,7 @@ impl Command for SubCommand {
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let head = call.head;
let target: i64 = call.req(engine_state, stack, 0)?;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty(head));
}
input.map(
move |value| operate(value, target, head),
engine_state.ctrlc.clone(),
@ -57,7 +54,10 @@ impl Command for SubCommand {
Example {
description: "Apply bits xor to two numbers",
example: "2 | bits xor 2",
result: Some(Value::test_int(0)),
result: Some(Value::Int {
val: 0,
span: Span::test_data(),
}),
},
Example {
description: "Apply logical xor to a list of numbers",
@ -77,15 +77,13 @@ fn operate(value: Value, target: i64, head: Span) -> Value {
val: val ^ target,
span,
},
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => value,
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
head,
// This line requires the Value::Error match above.
other.expect_span(),
error: ShellError::UnsupportedInput(
format!(
"Only integer values are supported, input type: {:?}",
other.get_type()
),
other.span().unwrap_or(head),
),
},
}

View File

@ -122,15 +122,13 @@ fn add(val: &Value, args: &Arguments, span: Span) -> Value {
val,
span: val_span,
} => add_impl(val, args, *val_span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with bytes.",
other.get_type()
),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -30,9 +30,7 @@ fn parse_range(range: Value, head: Span) -> Result<(isize, isize, Span), ShellEr
Value::List { mut vals, span } => {
if vals.len() != 2 {
return Err(ShellError::UnsupportedInput(
"More than two indices in range".to_string(),
"value originates from here".to_string(),
head,
"More than two indices given".to_string(),
span,
));
} else {
@ -40,14 +38,10 @@ fn parse_range(range: Value, head: Span) -> Result<(isize, isize, Span), ShellEr
let end = match end {
Value::Int { val, .. } => val.to_string(),
Value::String { val, .. } => val,
// Explicitly propagate errors instead of dropping them.
Value::Error { error } => return Err(error),
other => {
return Err(ShellError::UnsupportedInput(
"Only string or list<int> ranges are supported".into(),
format!("input type: {:?}", other.get_type()),
head,
other.expect_span(),
"could not perform subbytes. Expecting a string or int".to_string(),
other.span().unwrap_or(head),
))
}
};
@ -55,14 +49,10 @@ fn parse_range(range: Value, head: Span) -> Result<(isize, isize, Span), ShellEr
let start = match start {
Value::Int { val, .. } => val.to_string(),
Value::String { val, .. } => val,
// Explicitly propagate errors instead of dropping them.
Value::Error { error } => return Err(error),
other => {
return Err(ShellError::UnsupportedInput(
"Only string or list<int> ranges are supported".into(),
format!("input type: {:?}", other.get_type()),
head,
other.expect_span(),
"could not perform subbytes. Expecting a string or int".to_string(),
other.span().unwrap_or(head),
))
}
};
@ -76,21 +66,15 @@ fn parse_range(range: Value, head: Span) -> Result<(isize, isize, Span), ShellEr
None => {
return Err(ShellError::UnsupportedInput(
"could not perform subbytes".to_string(),
"with this range".to_string(),
head,
span,
))
}
}
}
// Explicitly propagate errors instead of dropping them.
Value::Error { error } => return Err(error),
other => {
return Err(ShellError::UnsupportedInput(
"could not perform subbytes".to_string(),
"with this range".to_string(),
head,
other.expect_span(),
other.span().unwrap_or(head),
))
}
};
@ -103,8 +87,6 @@ fn parse_range(range: Value, head: Span) -> Result<(isize, isize, Span), ShellEr
Err(_) => {
return Err(ShellError::UnsupportedInput(
"could not perform subbytes".to_string(),
"with this range".to_string(),
head,
span,
))
}
@ -118,8 +100,6 @@ fn parse_range(range: Value, head: Span) -> Result<(isize, isize, Span), ShellEr
Err(_) => {
return Err(ShellError::UnsupportedInput(
"could not perform subbytes".to_string(),
"with this range".to_string(),
head,
span,
))
}
@ -252,15 +232,13 @@ fn at(val: &Value, args: &Arguments, span: Span) -> Value {
val,
span: val_span,
} => at_impl(val, args, *val_span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with bytes.",
other.get_type()
),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}
@ -284,7 +262,7 @@ fn at_impl(input: &[u8], arg: &Arguments, span: Span) -> Value {
match start.cmp(&end) {
Ordering::Equal => Value::Binary { val: vec![], span },
Ordering::Greater => Value::Error {
error: ShellError::TypeMismatch(
error: ShellError::UnsupportedInput(
"End must be greater than or equal to Start".to_string(),
arg.arg_span,
),

View File

@ -52,12 +52,10 @@ impl Command for BytesBuild {
let val = eval_expression(engine_state, stack, expr)?;
match val {
Value::Binary { mut val, .. } => output.append(&mut val),
// Explicitly propagate errors instead of dropping them.
Value::Error { error } => return Err(error),
other => {
return Err(ShellError::TypeMismatch(
"only binary data arguments are supported".to_string(),
other.expect_span(),
return Err(ShellError::UnsupportedInput(
"only support expression which yields to binary data".to_string(),
other.span().unwrap_or(call.head),
))
}
}

View File

@ -2,7 +2,7 @@ use nu_engine::get_full_help;
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
Category, IntoPipelineData, PipelineData, Signature, Type, Value,
Category, IntoPipelineData, PipelineData, Signature, Value,
};
#[derive(Clone)]
@ -14,19 +14,13 @@ impl Command for Bytes {
}
fn signature(&self) -> Signature {
Signature::build("bytes")
.category(Category::Bytes)
.input_output_types(vec![(Type::Nothing, Type::String)])
Signature::build("bytes").category(Category::Bytes)
}
fn usage(&self) -> &str {
"Various commands for working with byte data"
}
fn extra_usage(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
@ -47,3 +41,15 @@ impl Command for Bytes {
.into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use crate::Bytes;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Bytes {})
}
}

View File

@ -54,16 +54,14 @@ impl Command for BytesCollect {
output_binary.append(&mut work_sep)
}
}
// Explicitly propagate errors instead of dropping them.
Value::Error { error } => return Err(error),
other => {
return Err(ShellError::OnlySupportsThisInputType(
"integer".into(),
other.get_type().to_string(),
call.head,
// This line requires the Value::Error match above.
other.expect_span(),
));
return Err(ShellError::UnsupportedInput(
format!(
"The element type is {}, this command only works with bytes.",
other.get_type()
),
other.span().unwrap_or(call.head),
))
}
}
}

View File

@ -68,17 +68,26 @@ impl Command for BytesEndsWith {
Example {
description: "Checks if binary ends with `0x[AA]`",
example: "0x[1F FF AA AA] | bytes ends-with 0x[AA]",
result: Some(Value::test_bool(true)),
result: Some(Value::Bool {
val: true,
span: Span::test_data(),
}),
},
Example {
description: "Checks if binary ends with `0x[FF AA AA]`",
example: "0x[1F FF AA AA] | bytes ends-with 0x[FF AA AA]",
result: Some(Value::test_bool(true)),
result: Some(Value::Bool {
val: true,
span: Span::test_data(),
}),
},
Example {
description: "Checks if binary ends with `0x[11]`",
example: "0x[1F FF AA AA] | bytes ends-with 0x[11]",
result: Some(Value::test_bool(false)),
result: Some(Value::Bool {
val: false,
span: Span::test_data(),
}),
},
]
}
@ -89,16 +98,17 @@ fn ends_with(val: &Value, args: &Arguments, span: Span) -> Value {
Value::Binary {
val,
span: val_span,
} => Value::boolean(val.ends_with(&args.pattern), *val_span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(),
} => Value::Bool {
val: val.ends_with(&args.pattern),
span: *val_span,
},
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"binary".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with bytes.",
other.get_type()
),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -132,15 +132,13 @@ fn index_of(val: &Value, args: &Arguments, span: Span) -> Value {
val,
span: val_span,
} => index_of_impl(val, args, *val_span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"binary".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with bytes.",
other.get_type()
),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -70,16 +70,17 @@ fn length(val: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value {
Value::Binary {
val,
span: val_span,
} => Value::int(val.len() as i64, *val_span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(),
} => Value::Int {
val: val.len() as i64,
span: *val_span,
},
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"binary".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with bytes.",
other.get_type()
),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -61,7 +61,7 @@ impl Command for BytesRemove {
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
let pattern_to_remove = call.req::<Spanned<Vec<u8>>>(engine_state, stack, 0)?;
if pattern_to_remove.item.is_empty() {
return Err(ShellError::TypeMismatch(
return Err(ShellError::UnsupportedInput(
"the pattern to remove cannot be empty".to_string(),
pattern_to_remove.span,
));
@ -139,15 +139,13 @@ fn remove(val: &Value, args: &Arguments, span: Span) -> Value {
val,
span: val_span,
} => remove_impl(val, args, *val_span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"binary".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with bytes.",
other.get_type()
),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}
@ -193,7 +191,7 @@ fn remove_impl(input: &[u8], arg: &Arguments, span: Span) -> Value {
right += 1;
}
}
// append the remaining thing to result, this can happened when
// append the remaing thing to result, this can happened when
// we have something to remove and remove_all is False.
let mut remain = input[left..].to_vec();
result.append(&mut remain);

View File

@ -61,7 +61,7 @@ impl Command for BytesReplace {
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
let find = call.req::<Spanned<Vec<u8>>>(engine_state, stack, 0)?;
if find.item.is_empty() {
return Err(ShellError::TypeMismatch(
return Err(ShellError::UnsupportedInput(
"the pattern to find cannot be empty".to_string(),
find.span,
));
@ -130,15 +130,13 @@ fn replace(val: &Value, args: &Arguments, span: Span) -> Value {
val,
span: val_span,
} => replace_impl(val, args, *val_span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"binary".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with bytes.",
other.get_type()
),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -81,15 +81,13 @@ fn reverse(val: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value {
span: *val_span,
}
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"binary".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with bytes.",
other.get_type()
),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -74,17 +74,26 @@ impl Command for BytesStartsWith {
Example {
description: "Checks if binary starts with `0x[1F FF AA]`",
example: "0x[1F FF AA AA] | bytes starts-with 0x[1F FF AA]",
result: Some(Value::test_bool(true)),
result: Some(Value::Bool {
val: true,
span: Span::test_data(),
}),
},
Example {
description: "Checks if binary starts with `0x[1F]`",
example: "0x[1F FF AA AA] | bytes starts-with 0x[1F]",
result: Some(Value::test_bool(true)),
result: Some(Value::Bool {
val: true,
span: Span::test_data(),
}),
},
Example {
description: "Checks if binary starts with `0x[1F]`",
example: "0x[1F FF AA AA] | bytes starts-with 0x[11]",
result: Some(Value::test_bool(false)),
result: Some(Value::Bool {
val: false,
span: Span::test_data(),
}),
},
]
}
@ -95,16 +104,17 @@ fn starts_with(val: &Value, args: &Arguments, span: Span) -> Value {
Value::Binary {
val,
span: val_span,
} => Value::boolean(val.starts_with(&args.pattern), *val_span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(),
} => Value::Bool {
val: val.starts_with(&args.pattern),
span: *val_span,
},
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"binary".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!(
"Input's type is {}. This command only works with bytes.",
other.get_type()
),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -53,7 +53,7 @@ impl Default for HashableValue {
fn default() -> Self {
HashableValue::Bool {
val: false,
span: Span::unknown(),
span: Span { start: 0, end: 0 },
}
}
}
@ -78,14 +78,13 @@ impl HashableValue {
Value::String { val, span } => Ok(HashableValue::String { val, span }),
Value::Binary { val, span } => Ok(HashableValue::Binary { val, span }),
// Explicitly propagate errors instead of dropping them.
Value::Error { error } => Err(error),
_ => Err(ShellError::UnsupportedInput(
"input value is not hashable".into(),
format!("input type: {:?}", value.get_type()),
span,
value.expect_span(),
)),
_ => {
let input_span = value.span().unwrap_or(span);
Err(ShellError::UnsupportedInput(
format!("input value {value:?} is not hashable"),
input_span,
))
}
}
}
@ -215,7 +214,7 @@ mod test {
];
for (val, expect_hashable_val) in values.into_iter() {
assert_eq!(
HashableValue::from_value(val, Span::unknown()).unwrap(),
HashableValue::from_value(val, Span { start: 0, end: 0 }).unwrap(),
expect_hashable_val
);
}
@ -246,7 +245,7 @@ mod test {
},
];
for v in values {
assert!(HashableValue::from_value(v, Span::unknown()).is_err())
assert!(HashableValue::from_value(v, Span { start: 0, end: 0 }).is_err())
}
}
@ -267,7 +266,7 @@ mod test {
for val in values.into_iter() {
let expected_val = val.clone();
assert_eq!(
HashableValue::from_value(val, Span::unknown())
HashableValue::from_value(val, Span { start: 0, end: 0 })
.unwrap()
.into_value(),
expected_val
@ -280,11 +279,14 @@ mod test {
assert_eq!(
HashableValue::Bool {
val: true,
span: Span::new(0, 1)
span: Span { start: 0, end: 1 }
},
HashableValue::Bool {
val: true,
span: Span::new(90, 1000)
span: Span {
start: 90,
end: 1000
}
}
)
}
@ -297,7 +299,7 @@ mod test {
assert!(set.contains(&HashableValue::Bool { val: true, span }));
// hashable value doesn't care about span.
let diff_span = Span::new(1, 2);
let diff_span = Span { start: 1, end: 2 };
set.insert(HashableValue::Bool {
val: true,
span: diff_span,

View File

@ -50,7 +50,7 @@ impl Command for Histogram {
},
Example {
description: "Compute a histogram for a list of numbers",
example: "[1 2 1] | histogram",
example: "echo [1 2 1] | histogram",
result: Some(Value::List {
vals: vec![Value::Record {
cols: vec!["value".to_string(), "count".to_string(), "quantile".to_string(), "percentage".to_string(), "frequency".to_string()],
@ -80,7 +80,7 @@ impl Command for Histogram {
},
Example {
description: "Compute a histogram for a list of numbers, and percentage is based on the maximum value",
example: "[1 2 3 1 1 1 2 2 1 1] | histogram --percentage-type relative",
example: "echo [1 2 3 1 1 1 2 2 1 1] | histogram --percentage-type relative",
result: None,
}
]
@ -98,11 +98,12 @@ impl Command for Histogram {
let frequency_name_arg = call.opt::<Spanned<String>>(engine_state, stack, 1)?;
let frequency_column_name = match frequency_name_arg {
Some(inner) => {
let span = inner.span;
if ["value", "count", "quantile", "percentage"].contains(&inner.item.as_str()) {
return Err(ShellError::TypeMismatch(
return Err(ShellError::UnsupportedInput(
"frequency-column-name can't be 'value', 'count' or 'percentage'"
.to_string(),
inner.span,
span,
));
}
inner.item
@ -118,7 +119,7 @@ impl Command for Histogram {
"normalize" => PercentageCalcMethod::Normalize,
"relative" => PercentageCalcMethod::Relative,
_ => {
return Err(ShellError::TypeMismatch(
return Err(ShellError::UnsupportedInput(
"calc method can only be 'normalize' or 'relative'".to_string(),
inner.span,
))
@ -136,8 +137,6 @@ impl Command for Histogram {
frequency_column_name,
calc_method,
span,
// Note that as_list() filters out Value::Error here.
data_as_value.expect_span(),
),
Err(e) => Err(e),
}
@ -150,7 +149,6 @@ fn run_histogram(
freq_column: String,
calc_method: PercentageCalcMethod,
head_span: Span,
list_span: Span,
) -> Result<PipelineData, ShellError> {
let mut inputs = vec![];
// convert from inputs to hashable values.
@ -159,24 +157,14 @@ fn run_histogram(
// some invalid input scenario needs to handle:
// Expect input is a list of hashable value, if one value is not hashable, throw out error.
for v in values {
match v {
// Propagate existing errors.
Value::Error { error } => return Err(error),
_ => {
let t = v.get_type();
let span = v.expect_span();
inputs.push(HashableValue::from_value(v, head_span).map_err(|_| {
ShellError::UnsupportedInput(
"Since --column-name was not provided, only lists of hashable values are supported.".to_string(),
format!(
"input type: {:?}", t
),
head_span,
span,
)
})?)
}
}
let current_span = v.span().unwrap_or(head_span);
inputs.push(HashableValue::from_value(v, head_span).map_err(|_| {
ShellError::UnsupportedInput(
"--column-name is not provided, can only support a list of simple value."
.to_string(),
current_span,
)
})?);
}
}
Some(ref col) => {
@ -198,17 +186,14 @@ fn run_histogram(
}
}
}
// Propagate existing errors.
Value::Error { error } => return Err(error),
_ => continue,
}
}
if inputs.is_empty() {
return Err(ShellError::CantFindColumn(
col_name.clone(),
return Err(ShellError::UnsupportedInput(
format!("expect input is table, and inputs doesn't contain any value which has {col_name} column"),
head_span,
list_span,
));
}
}
@ -264,33 +249,25 @@ fn histogram_impl(
let percentage = format!("{:.2}%", quantile * 100_f64);
let freq = "*".repeat((MAX_FREQ_COUNT * quantile).floor() as usize);
result.push((
count, // attach count first for easily sorting.
Value::Record {
cols: result_cols.clone(),
vals: vec![
val.into_value(),
Value::Int { val: count, span },
Value::Float {
val: quantile,
span,
},
Value::String {
val: percentage,
span,
},
Value::String { val: freq, span },
],
span,
},
));
result.push(Value::Record {
cols: result_cols.clone(),
vals: vec![
val.into_value(),
Value::Int { val: count, span },
Value::Float {
val: quantile,
span,
},
Value::String {
val: percentage,
span,
},
Value::String { val: freq, span },
],
span,
});
}
result.sort_by(|a, b| b.0.cmp(&a.0));
Value::List {
vals: result.into_iter().map(|x| x.1).collect(),
span,
}
.into_pipeline_data()
Value::List { vals: result, span }.into_pipeline_data()
}
#[cfg(test)]

View File

@ -44,14 +44,38 @@ impl Command for Fmt {
"upperhex".into(),
],
vals: vec![
Value::test_string("0b101010"),
Value::test_string("42"),
Value::test_string("42"),
Value::test_string("4.2e1"),
Value::test_string("0x2a"),
Value::test_string("0o52"),
Value::test_string("4.2E1"),
Value::test_string("0x2A"),
Value::String {
val: "0b101010".to_string(),
span: Span::test_data(),
},
Value::String {
val: "42".to_string(),
span: Span::test_data(),
},
Value::String {
val: "42".to_string(),
span: Span::test_data(),
},
Value::String {
val: "4.2e1".to_string(),
span: Span::test_data(),
},
Value::String {
val: "0x2a".to_string(),
span: Span::test_data(),
},
Value::String {
val: "0o52".to_string(),
span: Span::test_data(),
},
Value::String {
val: "4.2E1".to_string(),
span: Span::test_data(),
},
Value::String {
val: "0x2A".to_string(),
span: Span::test_data(),
},
],
span: Span::test_data(),
}),
@ -84,15 +108,10 @@ fn action(input: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value {
match input {
Value::Int { val, .. } => fmt_it(*val, span),
Value::Filesize { val, .. } => fmt_it(*val, span),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer or filesize".into(),
other.get_type().to_string(),
_ => Value::Error {
error: ShellError::UnsupportedInput(
format!("unsupported input type: {:?}", input.get_type()),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -177,24 +177,13 @@ pub fn action(input: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value {
val: int_to_endian(i64::from(*val)),
span,
},
Value::Duration { val, .. } => Value::Binary {
val: int_to_endian(*val),
span,
},
Value::Date { val, .. } => Value::Binary {
val: val.format("%c").to_string().as_bytes().to_vec(),
span,
},
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer, float, filesize, string, date, duration, binary or bool".into(),
other.get_type().to_string(),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
_ => Value::Error {
error: ShellError::UnsupportedInput("'into binary' for unsupported type".into(), span),
},
}
}

View File

@ -54,7 +54,7 @@ impl Command for SubCommand {
vec![
Example {
description: "Convert value to boolean in table",
example: "[[value]; ['false'] ['1'] [0] [1.0] [true]] | into bool value",
example: "echo [[value]; ['false'] ['1'] [0] [1.0] [true]] | into bool value",
result: Some(Value::List {
vals: vec![
Value::Record {
@ -163,15 +163,10 @@ fn action(input: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value {
Ok(val) => Value::Bool { val, span },
Err(error) => Value::Error { error },
},
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"bool, integer, float or string".into(),
other.get_type().to_string(),
_ => Value::Error {
error: ShellError::UnsupportedInput(
"'into bool' does not support this input".into(),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -2,7 +2,7 @@ use nu_engine::get_full_help;
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
Category, IntoPipelineData, PipelineData, Signature, Type, Value,
Category, IntoPipelineData, PipelineData, Signature, Value,
};
#[derive(Clone)]
@ -14,19 +14,13 @@ impl Command for Into {
}
fn signature(&self) -> Signature {
Signature::build("into")
.category(Category::Conversions)
.input_output_types(vec![(Type::Nothing, Type::String)])
Signature::build("into").category(Category::Conversions)
}
fn usage(&self) -> &str {
"Commands to convert data from one type to another."
}
fn extra_usage(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message."
}
fn run(
&self,
engine_state: &EngineState,
@ -47,3 +41,15 @@ impl Command for Into {
.into_pipeline_data())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Into {})
}
}

View File

@ -147,19 +147,41 @@ impl Command for SubCommand {
}
fn examples(&self) -> Vec<Example> {
let example_result_1 = |secs: i64, nsecs: u32| match Utc.timestamp_opt(secs, nsecs) {
LocalResult::Single(dt) => Some(Value::Date {
val: dt.into(),
span: Span::test_data(),
}),
_ => panic!("datetime: help example is invalid"),
let example_result_1 = |secs: i64, nsecs: u32| {
let dt = match Utc.timestamp_opt(secs, nsecs) {
LocalResult::Single(dt) => Some(dt),
_ => None,
};
match dt {
Some(dt) => Some(Value::Date {
val: dt.into(),
span: Span::test_data(),
}),
None => Some(Value::Error {
error: ShellError::UnsupportedInput(
"The given datetime representation is unsupported.".to_string(),
Span::test_data(),
),
}),
}
};
let example_result_2 = |millis: i64| match Utc.timestamp_millis_opt(millis) {
LocalResult::Single(dt) => Some(Value::Date {
val: dt.into(),
span: Span::test_data(),
}),
_ => panic!("datetime: help example is invalid"),
let example_result_2 = |millis: i64| {
let dt = match Utc.timestamp_millis_opt(millis) {
LocalResult::Single(dt) => Some(dt),
_ => None,
};
match dt {
Some(dt) => Some(Value::Date {
val: dt.into(),
span: Span::test_data(),
}),
None => Some(Value::Error {
error: ShellError::UnsupportedInput(
"The given datetime representation is unsupported.".to_string(),
Span::test_data(),
),
}),
}
};
vec![
Example {
@ -191,7 +213,7 @@ impl Command for SubCommand {
},
Example {
description:
"Convert a millisecond-precise timestamp",
"Convert timestamps like the sqlite history t",
example: "1656165681720 | into datetime",
result: example_result_2(1656165681720)
},
@ -209,16 +231,11 @@ fn action(input: &Value, args: &Arguments, head: Span) -> Value {
let timestamp = match input {
Value::Int { val, .. } => Ok(*val),
Value::String { val, .. } => val.parse::<i64>(),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => return input.clone(),
other => {
return Value::Error {
error: ShellError::OnlySupportsThisInputType(
"string and integer".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!("Expected string or int, got {} instead", other.get_type()),
head,
// This line requires the Value::Error match above.
other.expect_span(),
),
};
}
@ -231,68 +248,113 @@ fn action(input: &Value, args: &Arguments, head: Span) -> Value {
if ts.abs() > TIMESTAMP_BOUND {
return Value::Error {
error: ShellError::UnsupportedInput(
"timestamp is out of range; it should between -8e+12 and 8e+12".to_string(),
format!("timestamp is {:?}", ts),
"Given timestamp is out of range, it should between -8e+12 and 8e+12"
.to_string(),
head,
// Again, can safely unwrap this from here on
input.expect_span(),
),
};
}
macro_rules! match_datetime {
($expr:expr) => {
match $expr {
LocalResult::Single(dt) => Value::Date {
val: dt.into(),
span: head,
},
_ => {
return Value::Error {
error: ShellError::UnsupportedInput(
"The given local datetime representation is invalid.".into(),
format!("timestamp is {:?}", ts),
head,
head,
),
};
}
}
};
}
return match timezone {
// default to UTC
None => {
// be able to convert chrono::Utc::now()
match ts.to_string().len() {
x if x > 13 => Value::Date {
val: Utc.timestamp_nanos(ts).into(),
span: head,
let dt = match ts.to_string().len() {
x if x > 13 => Utc.timestamp_nanos(ts).into(),
x if x > 10 => match Utc.timestamp_millis_opt(ts) {
LocalResult::Single(dt) => dt.into(),
_ => {
return Value::Error {
// This error message is from chrono
error: ShellError::UnsupportedInput(
"The given local datetime representation is invalid."
.to_string(),
head,
),
};
}
},
x if x > 10 => match_datetime!(Utc.timestamp_millis_opt(ts)),
_ => match_datetime!(Utc.timestamp_opt(ts, 0)),
_ => match Utc.timestamp_opt(ts, 0) {
LocalResult::Single(dt) => dt.into(),
_ => {
return Value::Error {
error: ShellError::UnsupportedInput(
"The given local datetime representation is invalid."
.to_string(),
head,
),
}
}
},
};
Value::Date {
val: dt,
span: head,
}
}
Some(Spanned { item, span }) => match item {
Zone::Utc => match_datetime!(Utc.timestamp_opt(ts, 0)),
Zone::Local => match_datetime!(Local.timestamp_opt(ts, 0)),
Zone::Utc => match Utc.timestamp_opt(ts, 0) {
LocalResult::Single(val) => Value::Date {
val: val.into(),
span: head,
},
_ => Value::Error {
error: ShellError::UnsupportedInput(
"The given local datetime representation is invalid.".to_string(),
*span,
),
},
},
Zone::Local => match Local.timestamp_opt(ts, 0) {
LocalResult::Single(val) => Value::Date {
val: val.into(),
span: head,
},
_ => Value::Error {
error: ShellError::UnsupportedInput(
"The given local datetime representation is invalid.".to_string(),
*span,
),
},
},
Zone::East(i) => match FixedOffset::east_opt((*i as i32) * HOUR) {
Some(eastoffset) => match_datetime!(eastoffset.timestamp_opt(ts, 0)),
Some(eastoffset) => match eastoffset.timestamp_opt(ts, 0) {
LocalResult::Single(val) => Value::Date { val, span: head },
_ => Value::Error {
error: ShellError::UnsupportedInput(
"The given local datetime representation is invalid.".to_string(),
*span,
),
},
},
None => Value::Error {
error: ShellError::DatetimeParseError(*span),
error: ShellError::UnsupportedInput(
"The given local datetime representation is invalid.".to_string(),
*span,
),
},
},
Zone::West(i) => match FixedOffset::west_opt((*i as i32) * HOUR) {
Some(westoffset) => match_datetime!(westoffset.timestamp_opt(ts, 0)),
Some(westoffset) => match westoffset.timestamp_opt(ts, 0) {
LocalResult::Single(val) => Value::Date { val, span: head },
_ => Value::Error {
error: ShellError::UnsupportedInput(
"The given local datetime representation is invalid.".to_string(),
*span,
),
},
},
None => Value::Error {
error: ShellError::DatetimeParseError(*span),
error: ShellError::UnsupportedInput(
"The given local datetime representation is invalid.".to_string(),
*span,
),
},
},
Zone::Error => Value::Error {
// This is an argument error, not an input error
error: ShellError::TypeMismatch(
"Invalid timezone or offset".to_string(),
error: ShellError::UnsupportedInput(
"Cannot convert given timezone or offset to timestamp".to_string(),
*span,
),
},
@ -329,15 +391,10 @@ fn action(input: &Value, args: &Arguments, head: Span) -> Value {
},
}
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"string".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
format!("Expected string, got {} instead", other.get_type()),
head,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}

View File

@ -86,7 +86,7 @@ fn action(input: &Value, _args: &CellPathOnlyArgs, head: Span) -> Value {
let other = s.trim();
match other.parse::<f64>() {
Ok(x) => Value::float(x, head),
Ok(x) => Value::Float { val: x, span: head },
Err(reason) => Value::Error {
error: ShellError::CantConvert(
"float".to_string(),
@ -97,7 +97,10 @@ fn action(input: &Value, _args: &CellPathOnlyArgs, head: Span) -> Value {
},
}
}
Value::Int { val: v, span } => Value::float(*v as f64, *span),
Value::Int { val: v, span } => Value::Float {
val: *v as f64,
span: *span,
},
Value::Bool { val: b, span } => Value::Float {
val: match b {
true => 1.0,
@ -105,17 +108,18 @@ fn action(input: &Value, _args: &CellPathOnlyArgs, head: Span) -> Value {
},
span: *span,
},
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"string, integer or bool".into(),
other.get_type().to_string(),
head,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
other => {
let span = other.span();
match span {
Ok(s) => {
let got = format!("Expected a string, got {} instead", other.get_type());
Value::Error {
error: ShellError::UnsupportedInput(got, s),
}
}
Err(e) => Value::Error { error: e },
}
}
}
}

View File

@ -65,8 +65,7 @@ impl Command for SubCommand {
vec![
Example {
description: "Convert string to duration in table",
example:
"[[value]; ['1sec'] ['2min'] ['3hr'] ['4day'] ['5wk']] | into duration value",
example: "echo [[value]; ['1sec'] ['2min'] ['3hr'] ['4day'] ['5wk']] | into duration value",
result: Some(Value::List {
vals: vec![
Value::Record {
@ -468,11 +467,9 @@ fn action(
}
} else {
Value::Error {
error: ShellError::CantConvert(
"string".into(),
"duration".into(),
error: ShellError::UnsupportedInput(
"'into duration' does not support this string input".into(),
span,
None,
),
}
}
@ -483,15 +480,10 @@ fn action(
}
}
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"string or duration".into(),
other.get_type().to_string(),
_ => Value::Error {
error: ShellError::UnsupportedInput(
"'into duration' does not support this input".into(),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}
@ -510,7 +502,7 @@ mod test {
#[test]
fn turns_ns_to_duration() {
let span = Span::new(0, 2);
let span = Span::test_data();
let word = Value::test_string("3ns");
let expected = Value::Duration { val: 3, span };
let convert_duration = None;
@ -521,7 +513,7 @@ mod test {
#[test]
fn turns_us_to_duration() {
let span = Span::new(0, 2);
let span = Span::test_data();
let word = Value::test_string("4us");
let expected = Value::Duration {
val: 4 * 1000,
@ -535,7 +527,7 @@ mod test {
#[test]
fn turns_ms_to_duration() {
let span = Span::new(0, 2);
let span = Span::test_data();
let word = Value::test_string("5ms");
let expected = Value::Duration {
val: 5 * 1000 * 1000,
@ -549,7 +541,7 @@ mod test {
#[test]
fn turns_sec_to_duration() {
let span = Span::new(0, 3);
let span = Span::test_data();
let word = Value::test_string("1sec");
let expected = Value::Duration {
val: 1000 * 1000 * 1000,
@ -563,7 +555,7 @@ mod test {
#[test]
fn turns_min_to_duration() {
let span = Span::new(0, 3);
let span = Span::test_data();
let word = Value::test_string("7min");
let expected = Value::Duration {
val: 7 * 60 * 1000 * 1000 * 1000,
@ -577,7 +569,7 @@ mod test {
#[test]
fn turns_hr_to_duration() {
let span = Span::new(0, 3);
let span = Span::test_data();
let word = Value::test_string("42hr");
let expected = Value::Duration {
val: 42 * 60 * 60 * 1000 * 1000 * 1000,
@ -591,7 +583,7 @@ mod test {
#[test]
fn turns_day_to_duration() {
let span = Span::new(0, 5);
let span = Span::test_data();
let word = Value::test_string("123day");
let expected = Value::Duration {
val: 123 * 24 * 60 * 60 * 1000 * 1000 * 1000,
@ -605,7 +597,7 @@ mod test {
#[test]
fn turns_wk_to_duration() {
let span = Span::new(0, 2);
let span = Span::test_data();
let word = Value::test_string("3wk");
let expected = Value::Duration {
val: 3 * 7 * 24 * 60 * 60 * 1000 * 1000 * 1000,

View File

@ -116,18 +116,20 @@ pub fn action(input: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value {
val: 0,
span: value_span,
},
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"string and integer".into(),
other.get_type().to_string(),
span,
_ => Value::Error {
error: ShellError::UnsupportedInput(
"'into filesize' for unsupported type".into(),
value_span,
),
},
}
} else {
// Propagate existing errors
input.clone()
Value::Error {
error: ShellError::UnsupportedInput(
"'into filesize' for unsupported type".into(),
span,
),
}
}
}
fn int_from_string(a_string: &str, span: Span) -> Result<i64, ShellError> {

View File

@ -70,7 +70,7 @@ impl Command for SubCommand {
let radix: u32 = match radix {
Some(Value::Int { val, span }) => {
if !(2..=36).contains(&val) {
return Err(ShellError::TypeMismatch(
return Err(ShellError::UnsupportedInput(
"Radix must lie in the range [2, 36]".to_string(),
span,
));
@ -92,7 +92,7 @@ impl Command for SubCommand {
vec![
Example {
description: "Convert string to integer in table",
example: "[[num]; ['-5'] [4] [1.5]] | into int num",
example: "echo [[num]; ['-5'] [4] [1.5]] | into int num",
result: None,
},
Example {
@ -113,7 +113,10 @@ impl Command for SubCommand {
Example {
description: "Convert file size to integer",
example: "4KB | into int",
result: Some(Value::test_int(4000)),
result: Some(Value::Int {
val: 4000,
span: Span::test_data(),
}),
},
Example {
description: "Convert bool to integer",
@ -187,11 +190,9 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
Ok(v) => v,
_ => {
return Value::Error {
error: ShellError::CantConvert(
"float".to_string(),
"integer".to_string(),
error: ShellError::UnsupportedInput(
"Could not convert float to integer".to_string(),
span,
None,
),
}
}
@ -221,7 +222,6 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
val: val.timestamp(),
span,
},
Value::Duration { val, .. } => Value::Int { val: *val, span },
Value::Binary { val, span } => {
use byteorder::{BigEndian, ByteOrder, LittleEndian};
@ -233,25 +233,26 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
}
val.resize(8, 0);
Value::int(LittleEndian::read_i64(&val), *span)
Value::Int {
val: LittleEndian::read_i64(&val),
span: *span,
}
} else {
while val.len() < 8 {
val.insert(0, 0);
}
val.resize(8, 0);
Value::int(BigEndian::read_i64(&val), *span)
Value::Int {
val: BigEndian::read_i64(&val),
span: *span,
}
}
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"integer, float, filesize, date, string, binary, duration or bool".into(),
other.get_type().to_string(),
_ => Value::Error {
error: ShellError::UnsupportedInput(
format!("'into int' for unsupported type '{}'", input.get_type()),
span,
// This line requires the Value::Error match above.
other.expect_span(),
),
},
}
@ -268,13 +269,13 @@ fn convert_int(input: &Value, head: Span, radix: u32) -> Value {
// octal
{
match int_from_string(val, head) {
Ok(x) => return Value::int(x, head),
Ok(x) => return Value::Int { val: x, span: head },
Err(e) => return Value::Error { error: e },
}
} else if val.starts_with("00") {
// It's a padded string
match i64::from_str_radix(val, radix) {
Ok(n) => return Value::int(n, head),
Ok(n) => return Value::Int { val: n, span: head },
Err(e) => {
return Value::Error {
error: ShellError::CantConvert(
@ -289,22 +290,17 @@ fn convert_int(input: &Value, head: Span, radix: u32) -> Value {
}
val.to_string()
}
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => return input.clone(),
other => {
_ => {
return Value::Error {
error: ShellError::OnlySupportsThisInputType(
"string and integer".into(),
other.get_type().to_string(),
error: ShellError::UnsupportedInput(
"only strings or integers are supported".to_string(),
head,
// This line requires the Value::Error match above.
other.expect_span(),
),
};
}
}
};
match i64::from_str_radix(i.trim(), radix) {
Ok(n) => Value::int(n, head),
Ok(n) => Value::Int { val: n, span: head },
Err(_reason) => Value::Error {
error: ShellError::CantConvert("string".to_string(), "int".to_string(), head, None),
},

View File

@ -49,7 +49,7 @@ impl Command for SubCommand {
vec![
Example {
description: "Convert from one row table to record",
example: "[[value]; [false]] | into record",
example: "echo [[value]; [false]] | into record",
result: Some(Value::Record {
cols: vec!["value".to_string()],
vals: vec![Value::boolean(false, span)],
@ -183,14 +183,10 @@ fn into_record(
Value::Record { cols, vals, span }
}
Value::Record { cols, vals, span } => Value::Record { cols, vals, span },
Value::Error { .. } => input,
other => Value::Error {
error: ShellError::OnlySupportsThisInputType(
"string".into(),
other.get_type().to_string(),
call.head,
// This line requires the Value::Error match above.
other.expect_span(),
error: ShellError::UnsupportedInput(
"'into record' does not support this input".into(),
other.span().unwrap_or(call.head),
),
},
};

View File

@ -79,22 +79,34 @@ impl Command for SubCommand {
Example {
description: "convert integer to string and append three decimal places",
example: "5 | into string -d 3",
result: Some(Value::test_string("5.000")),
result: Some(Value::String {
val: "5.000".to_string(),
span: Span::test_data(),
}),
},
Example {
description: "convert decimal to string and round to nearest integer",
example: "1.7 | into string -d 0",
result: Some(Value::test_string("2")),
result: Some(Value::String {
val: "2".to_string(),
span: Span::test_data(),
}),
},
Example {
description: "convert decimal to string",
example: "1.7 | into string -d 1",
result: Some(Value::test_string("1.7")),
result: Some(Value::String {
val: "1.7".to_string(),
span: Span::test_data(),
}),
},
Example {
description: "convert decimal to string and limit to 2 decimals",
example: "1.734 | into string -d 2",
result: Some(Value::test_string("1.73")),
result: Some(Value::String {
val: "1.73".to_string(),
span: Span::test_data(),
}),
},
Example {
description: "try to convert decimal to string and provide negative decimal points",
@ -111,17 +123,26 @@ impl Command for SubCommand {
Example {
description: "convert decimal to string",
example: "4.3 | into string",
result: Some(Value::test_string("4.3")),
result: Some(Value::String {
val: "4.3".to_string(),
span: Span::test_data(),
}),
},
Example {
description: "convert string to string",
example: "'1234' | into string",
result: Some(Value::test_string("1234")),
result: Some(Value::String {
val: "1234".to_string(),
span: Span::test_data(),
}),
},
Example {
description: "convert boolean to string",
example: "true | into string",
result: Some(Value::test_string("true")),
result: Some(Value::String {
val: "true".to_string(),
span: Span::test_data(),
}),
},
// TODO: This should work but does not; see https://github.com/nushell/nushell/issues/7032
// Example {
@ -154,7 +175,7 @@ fn string_helper(
let decimals_value: Option<i64> = call.get_flag(engine_state, stack, "decimals")?;
if let Some(decimal_val) = decimals_value {
if decimals && decimal_val.is_negative() {
return Err(ShellError::TypeMismatch(
return Err(ShellError::UnsupportedInput(
"Cannot accept negative integers for decimals arguments".to_string(),
head,
));
@ -251,11 +272,9 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
vals: _,
span: _,
} => Value::Error {
error: ShellError::CantConvert(
"record".into(),
"string".into(),
error: ShellError::UnsupportedInput(
"Cannot convert Record into string".to_string(),
span,
Some("try using the `to nuon` command".into()),
),
},
Value::Binary { .. } => Value::Error {

View File

@ -43,10 +43,10 @@ impl Command for Alias {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -37,13 +37,14 @@ impl Command for Ast {
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let pipeline: Spanned<String> = call.req(engine_state, stack, 0)?;
let mut working_set = StateWorkingSet::new(engine_state);
let (output, err) = parse(&mut working_set, None, pipeline.item.as_bytes(), false, &[]);
eprintln!("output: {:#?}\nerror: {:#?}", output, err);
Ok(PipelineData::empty())
Ok(PipelineData::new(head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,104 +0,0 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type};
#[derive(Clone)]
pub struct Const;
impl Command for Const {
fn name(&self) -> &str {
"const"
}
fn usage(&self) -> &str {
"Create a parse-time constant."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("const")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.allow_variants_without_examples(true)
.required("const_name", SyntaxShape::VarWithOptType, "constant name")
.required(
"initial_value",
SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::Expression)),
"equals sign followed by constant value",
)
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn search_terms(&self) -> Vec<&str> {
vec!["set", "let"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let var_id = call
.positional_nth(0)
.expect("checked through parser")
.as_var()
.expect("internal error: missing variable");
if let Some(constval) = engine_state.find_constant(var_id, &[]) {
// Instead of creating a second copy of the value in the stack, we could change
// stack.get_var() to check engine_state.find_constant().
stack.add_var(var_id, constval.clone());
Ok(PipelineData::empty())
} else {
Err(ShellError::NushellFailedSpanned(
"Missing Constant".to_string(),
"constant not added by the parser".to_string(),
call.head,
))
}
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Create a new parse-time constant.",
example: "const x = 10",
result: None,
},
Example {
description: "Create a composite constant value",
example: "const x = { a: 10, b: 20 }",
result: None,
},
]
}
}
#[cfg(test)]
mod test {
use nu_protocol::engine::CommandType;
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Const {})
}
#[test]
fn test_command_type() {
assert!(matches!(Const.command_type(), CommandType::Keyword));
}
}

View File

@ -39,8 +39,6 @@ impl Command for Debug {
let config = engine_state.get_config().clone();
let raw = call.has_flag("raw");
// Should PipelineData::Empty result in an error here?
input.map(
move |x| {
if raw {
@ -76,7 +74,7 @@ impl Command for Debug {
},
Example {
description: "Debug print a table",
example: "[[version patch]; [0.1.0 false] [0.1.1 true] [0.2.0 false]] | debug",
example: "echo [[version patch]; [0.1.0 false] [0.1.1 true] [0.2.0 false]] | debug",
result: Some(Value::List {
vals: vec![
Value::test_string("{version: 0.1.0, patch: false}"),

View File

@ -36,10 +36,10 @@ impl Command for Def {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,6 +1,6 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, Signature, SyntaxShape, Type, Value};
use nu_protocol::{Category, Example, PipelineData, Signature, Span, SyntaxShape, Type, Value};
#[derive(Clone)]
pub struct DefEnv;
@ -62,17 +62,20 @@ def-env cd_with_fallback [arg = ""] {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Set environment variable by call a custom command",
example: r#"def-env foo [] { let-env BAR = "BAZ" }; foo; $env.BAR"#,
result: Some(Value::test_string("BAZ")),
result: Some(Value::String {
val: "BAZ".to_string(),
span: Span::test_data(),
}),
}]
}
}

View File

@ -19,11 +19,6 @@ impl Command for Describe {
fn signature(&self) -> Signature {
Signature::build("describe")
.input_output_types(vec![(Type::Any, Type::String)])
.switch(
"no-collect",
"do not collect streams of structured data",
Some('n'),
)
.category(Category::Core)
}
@ -35,58 +30,32 @@ impl Command for Describe {
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
if matches!(input, PipelineData::ExternalStream { .. }) {
Ok(PipelineData::Value(
Value::string("raw input", call.head),
None,
))
} else {
let value = input.into_value(call.head);
let description = match value {
Value::CustomValue { val, .. } => val.value_string(),
_ => value.get_type().to_string(),
};
let no_collect: bool = call.has_flag("no-collect");
let description = match input {
PipelineData::ExternalStream { .. } => "raw input".into(),
PipelineData::ListStream(_, _) => {
if no_collect {
"stream".into()
} else {
let value = input.into_value(head);
let base_description = match value {
Value::CustomValue { val, .. } => val.value_string(),
_ => value.get_type().to_string(),
};
format!("{base_description} (stream)")
}
Ok(Value::String {
val: description,
span: head,
}
_ => {
let value = input.into_value(head);
match value {
Value::CustomValue { val, .. } => val.value_string(),
_ => value.get_type().to_string(),
}
}
};
Ok(Value::String {
val: description,
span: head,
.into_pipeline_data())
}
.into_pipeline_data())
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Describe the type of a string",
example: "'hello' | describe",
result: Some(Value::test_string("string")),
},
Example {
description: "Describe a stream of data, collecting it first",
example: "[1 2 3] | each {|i| $i} | describe",
result: Some(Value::test_string("list<int> (stream)")),
},
Example {
description: "Describe the input but do not collect streams",
example: "[1 2 3] | each {|i| $i} | describe --no-collect",
result: Some(Value::test_string("stream")),
},
]
vec![Example {
description: "Describe the type of a string",
example: "'hello' | describe",
result: Some(Value::test_string("string")),
}]
}
fn search_terms(&self) -> Vec<&str> {

View File

@ -14,7 +14,7 @@ impl Command for Do {
}
fn usage(&self) -> &str {
"Run a closure, providing it with the pipeline input"
"Run a block"
}
fn signature(&self) -> Signature {
@ -23,25 +23,25 @@ impl Command for Do {
.input_output_types(vec![(Type::Any, Type::Any)])
.switch(
"ignore-errors",
"ignore errors as the closure runs",
"ignore errors as the block runs",
Some('i'),
)
.switch(
"ignore-shell-errors",
"ignore shell errors as the closure runs",
"ignore shell errors as the block runs",
Some('s'),
)
.switch(
"ignore-program-errors",
"ignore external program errors as the closure runs",
"ignore program errors as the block runs",
Some('p'),
)
.switch(
"capture-errors",
"catch errors as the closure runs, and return them",
"capture errors as the block runs and return it",
Some('c'),
)
.rest("rest", SyntaxShape::Any, "the parameter(s) for the closure")
.rest("rest", SyntaxShape::Any, "the parameter(s) for the block")
.category(Category::Core)
}
@ -169,9 +169,9 @@ impl Command for Do {
trim_end_newline,
}),
Ok(PipelineData::Value(Value::Error { .. }, ..)) if ignore_shell_errors => {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
Err(_) if ignore_shell_errors => Ok(PipelineData::empty()),
Err(_) if ignore_shell_errors => Ok(PipelineData::new(call.head)),
r => r,
}
}
@ -179,27 +179,22 @@ impl Command for Do {
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Run the closure",
description: "Run the block",
example: r#"do { echo hello }"#,
result: Some(Value::test_string("hello")),
},
Example {
description: "Run a stored first-class closure",
example: r#"let text = "I am enclosed"; let hello = {|| echo $text}; do $hello"#,
result: Some(Value::test_string("I am enclosed")),
},
Example {
description: "Run the closure and ignore both shell and external program errors",
description: "Run the block and ignore both shell and program errors",
example: r#"do -i { thisisnotarealcommand }"#,
result: None,
},
Example {
description: "Run the closure and ignore shell errors",
description: "Run the block and ignore shell errors",
example: r#"do -s { thisisnotarealcommand }"#,
result: None,
},
Example {
description: "Run the closure and ignore external program errors",
description: "Run the block and ignore program errors",
example: r#"do -p { nu -c 'exit 1' }; echo "I'll still run""#,
result: None,
},
@ -209,12 +204,12 @@ impl Command for Do {
result: None,
},
Example {
description: "Run the closure, with a positional parameter",
description: "Run the block, with a positional parameter",
example: r#"do {|x| 100 + $x } 77"#,
result: Some(Value::test_int(177)),
},
Example {
description: "Run the closure, with input",
description: "Run the block, with input",
example: r#"77 | do {|x| 100 + $in }"#,
result: None, // TODO: returns 177
},

View File

@ -51,7 +51,13 @@ little reason to use this over just writing the values as-is."#
std::cmp::Ordering::Equal => PipelineData::Value(to_be_echoed[0].clone(), None),
// When there are no elements, we echo the empty string
std::cmp::Ordering::Less => PipelineData::Value(Value::string("", call.head), None),
std::cmp::Ordering::Less => PipelineData::Value(
Value::String {
val: "".to_string(),
span: call.head,
},
None,
),
}
})
}

View File

@ -2,7 +2,7 @@ use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value,
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Value,
};
#[derive(Clone)]
@ -15,7 +15,6 @@ impl Command for ErrorMake {
fn signature(&self) -> Signature {
Signature::build("error make")
.input_output_types(vec![(Type::Nothing, Type::Error)])
.required("error_struct", SyntaxShape::Record, "the error to create")
.switch(
"unspanned",
@ -109,7 +108,10 @@ fn make_error(value: &Value, throw_span: Option<Span>) -> Option<ShellError> {
) => Some(ShellError::GenericError(
message,
label_text,
Some(Span::new(start as usize, end as usize)),
Some(Span {
start: start as usize,
end: end as usize,
}),
None,
Vec::new(),
)),

View File

@ -2,7 +2,7 @@ use nu_engine::get_full_help;
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
Category, Example, IntoPipelineData, PipelineData, Signature, Type, Value,
Category, Example, IntoPipelineData, PipelineData, Signature, Span, Type, Value,
};
#[derive(Clone)]
@ -56,7 +56,10 @@ impl Command for ExportCommand {
vec![Example {
description: "Export a definition from a module",
example: r#"module utils { export def my-command [] { "hello" } }; use utils my-command; my-command"#,
result: Some(Value::test_string("hello")),
result: Some(Value::String {
val: "hello".to_string(),
span: Span::test_data(),
}),
}]
}

View File

@ -39,10 +39,10 @@ impl Command for ExportAlias {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,6 +1,6 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, Signature, SyntaxShape, Type, Value};
use nu_protocol::{Category, Example, PipelineData, Signature, Span, SyntaxShape, Type, Value};
#[derive(Clone)]
pub struct ExportDef;
@ -36,17 +36,20 @@ impl Command for ExportDef {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Define a custom command in a module and call it",
example: r#"module spam { export def foo [] { "foo" } }; use spam foo; foo"#,
result: Some(Value::test_string("foo")),
result: Some(Value::String {
val: "foo".to_string(),
span: Span::test_data(),
}),
}]
}

View File

@ -1,6 +1,6 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, Signature, SyntaxShape, Type, Value};
use nu_protocol::{Category, Example, PipelineData, Signature, Span, SyntaxShape, Type, Value};
#[derive(Clone)]
pub struct ExportDefEnv;
@ -62,17 +62,20 @@ export def-env cd_with_fallback [arg = ""] {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Define a custom command that participates in the environment in a module and call it",
example: r#"module foo { export def-env bar [] { let-env FOO_BAR = "BAZ" } }; use foo bar; bar; $env.FOO_BAR"#,
result: Some(Value::test_string("BAZ")),
result: Some(Value::String {
val: "BAZ".to_string(),
span: Span::test_data(),
}),
}]
}

View File

@ -35,10 +35,10 @@ impl Command for ExportExtern {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,6 +1,6 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, Signature, SyntaxShape, Type, Value};
use nu_protocol::{Category, Example, PipelineData, Signature, Span, SyntaxShape, Type, Value};
#[derive(Clone)]
pub struct ExportUse;
@ -17,12 +17,7 @@ impl Command for ExportUse {
fn signature(&self) -> nu_protocol::Signature {
Signature::build("export use")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required("module", SyntaxShape::String, "Module or module file")
.optional(
"members",
SyntaxShape::Any,
"Which members of the module to import",
)
.required("pattern", SyntaxShape::ImportPattern, "import pattern")
.category(Category::Core)
}
@ -39,10 +34,10 @@ impl Command for ExportUse {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {
@ -53,7 +48,10 @@ impl Command for ExportUse {
use eggs foo
foo
"#,
result: Some(Value::test_string("foo")),
result: Some(Value::String {
val: "foo".to_string(),
span: Span::test_data(),
}),
}]
}

View File

@ -35,10 +35,10 @@ impl Command for Extern {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -2,7 +2,7 @@ use nu_engine::{eval_block, eval_expression, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Block, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, ListStream, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
Category, Example, ListStream, PipelineData, ShellError, Signature, SyntaxShape, Value,
};
#[derive(Clone)]
@ -19,8 +19,6 @@ impl Command for For {
fn signature(&self) -> nu_protocol::Signature {
Signature::build("for")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.allow_variants_without_examples(true)
.required(
"var_name",
SyntaxShape::VarWithOptType,
@ -93,7 +91,13 @@ impl Command for For {
if numbered {
Value::Record {
cols: vec!["index".into(), "item".into()],
vals: vec![Value::int(idx as i64, head), x],
vals: vec![
Value::Int {
val: idx as i64,
span: head,
},
x,
],
span: head,
}
} else {
@ -106,7 +110,7 @@ impl Command for For {
&engine_state,
stack,
&block,
PipelineData::empty(),
PipelineData::new(head),
redirect_stdout,
redirect_stderr,
) {
@ -120,10 +124,7 @@ impl Command for For {
return Err(err);
}
Ok(pipeline) => {
let exit_code = pipeline.print(&engine_state, stack, false, false)?;
if exit_code != 0 {
break;
}
pipeline.into_value(head);
}
}
}
@ -135,7 +136,13 @@ impl Command for For {
if numbered {
Value::Record {
cols: vec!["index".into(), "item".into()],
vals: vec![Value::int(idx as i64, head), x],
vals: vec![
Value::Int {
val: idx as i64,
span: head,
},
x,
],
span: head,
}
} else {
@ -148,7 +155,7 @@ impl Command for For {
&engine_state,
stack,
&block,
PipelineData::empty(),
PipelineData::new(head),
redirect_stdout,
redirect_stderr,
) {
@ -162,10 +169,7 @@ impl Command for For {
return Err(err);
}
Ok(pipeline) => {
let exit_code = pipeline.print(&engine_state, stack, false, false)?;
if exit_code != 0 {
break;
}
pipeline.into_value(head);
}
}
}
@ -177,14 +181,14 @@ impl Command for For {
&engine_state,
stack,
&block,
PipelineData::empty(),
PipelineData::new(head),
redirect_stdout,
redirect_stderr,
)?
.into_value(head);
}
}
Ok(PipelineData::empty())
Ok(PipelineData::new(head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,18 +1,17 @@
use crate::help_aliases::help_aliases;
use crate::help_commands::help_commands;
use crate::help_modules::help_modules;
use fancy_regex::Regex;
use nu_ansi_term::{
Color::{Red, White},
Color::{Default, Red, White},
Style,
};
use nu_engine::CallExt;
use nu_color_config::get_color_config;
use nu_engine::{get_full_help, CallExt};
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
span, Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Spanned,
SyntaxShape, Type, Value,
span, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
use std::borrow::Borrow;
#[derive(Clone)]
pub struct Help;
@ -27,7 +26,7 @@ impl Command for Help {
.rest(
"rest",
SyntaxShape::String,
"the name of command, alias or module to get help on",
"the name of command to get help on",
)
.named(
"find",
@ -39,11 +38,7 @@ impl Command for Help {
}
fn usage(&self) -> &str {
"Display help information about different parts of Nushell."
}
fn extra_usage(&self) -> &str {
r#"`help word` searches for "word" in commands, aliases and modules, in that order."#
"Display help information about commands."
}
fn run(
@ -53,18 +48,275 @@ impl Command for Help {
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
help(engine_state, stack, call)
}
if rest.is_empty() && find.is_none() {
let msg = r#"Welcome to Nushell.
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "show all commands and sub-commands",
example: "help commands",
result: None,
},
Example {
description: "show help for single command",
example: "help match",
result: None,
},
Example {
description: "show help for single sub-command",
example: "help str lpad",
result: None,
},
Example {
description: "search for string in command names, usage and search terms",
example: "help --find char",
result: None,
},
]
}
}
fn help(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
let commands = engine_state.get_decl_ids_sorted(false);
let config = engine_state.get_config();
let color_hm = get_color_config(config);
let default_style = Style::new().fg(Default).on(Default);
let string_style = match color_hm.get("string") {
Some(style) => style,
None => &default_style,
};
if let Some(f) = find {
let org_search_string = f.item.clone();
let search_string = f.item.to_lowercase();
let mut found_cmds_vec = Vec::new();
for decl_id in commands {
let mut cols = vec![];
let mut vals = vec![];
let decl = engine_state.get_decl(decl_id);
let sig = decl.signature().update_from_command(decl.borrow());
let signatures = sig.to_string();
let key = sig.name;
let usage = sig.usage;
let search_terms = sig.search_terms;
let matches_term = if !search_terms.is_empty() {
search_terms
.iter()
.any(|term| term.to_lowercase().contains(&search_string))
} else {
false
};
let key_match = key.to_lowercase().contains(&search_string);
let usage_match = usage.to_lowercase().contains(&search_string);
if key_match || usage_match || matches_term {
cols.push("name".into());
vals.push(Value::String {
val: if key_match {
highlight_search_string(&key, &org_search_string, string_style)?
} else {
key
},
span: head,
});
cols.push("category".into());
vals.push(Value::String {
val: sig.category.to_string(),
span: head,
});
cols.push("command_type".into());
vals.push(Value::String {
val: format!("{:?}", decl.command_type()).to_lowercase(),
span: head,
});
cols.push("usage".into());
vals.push(Value::String {
val: if usage_match {
highlight_search_string(&usage, &org_search_string, string_style)?
} else {
usage
},
span: head,
});
cols.push("signatures".into());
vals.push(Value::String {
val: if decl.is_parser_keyword() {
"".to_string()
} else {
signatures
},
span: head,
});
cols.push("search_terms".into());
vals.push(if search_terms.is_empty() {
Value::nothing(head)
} else {
Value::String {
val: if matches_term {
search_terms
.iter()
.map(|term| {
if term.to_lowercase().contains(&search_string) {
match highlight_search_string(
term,
&org_search_string,
string_style,
) {
Ok(s) => s,
Err(_) => {
string_style.paint(term.to_string()).to_string()
}
}
} else {
string_style.paint(term.to_string()).to_string()
}
})
.collect::<Vec<_>>()
.join(", ")
} else {
search_terms.join(", ")
},
span: head,
}
});
found_cmds_vec.push(Value::Record {
cols,
vals,
span: head,
});
}
}
return Ok(found_cmds_vec
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()));
}
if !rest.is_empty() {
let mut found_cmds_vec = Vec::new();
if rest[0].item == "commands" {
for decl_id in commands {
let mut cols = vec![];
let mut vals = vec![];
let decl = engine_state.get_decl(decl_id);
let sig = decl.signature().update_from_command(decl.borrow());
let signatures = sig.to_string();
let key = sig.name;
let usage = sig.usage;
let search_terms = sig.search_terms;
cols.push("name".into());
vals.push(Value::String {
val: key,
span: head,
});
cols.push("category".into());
vals.push(Value::String {
val: sig.category.to_string(),
span: head,
});
cols.push("command_type".into());
vals.push(Value::String {
val: format!("{:?}", decl.command_type()).to_lowercase(),
span: head,
});
cols.push("usage".into());
vals.push(Value::String {
val: usage,
span: head,
});
cols.push("signatures".into());
vals.push(Value::String {
val: if decl.is_parser_keyword() {
"".to_string()
} else {
signatures
},
span: head,
});
cols.push("search_terms".into());
vals.push(if search_terms.is_empty() {
Value::nothing(head)
} else {
Value::String {
val: search_terms.join(", "),
span: head,
}
});
found_cmds_vec.push(Value::Record {
cols,
vals,
span: head,
});
}
Ok(found_cmds_vec
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()))
} else {
let mut name = String::new();
for r in &rest {
if !name.is_empty() {
name.push(' ');
}
name.push_str(&r.item);
}
let output = engine_state
.get_signatures_with_examples(false)
.iter()
.filter(|(signature, _, _, _, _)| signature.name == name)
.map(|(signature, examples, _, _, is_parser_keyword)| {
get_full_help(signature, examples, engine_state, stack, *is_parser_keyword)
})
.collect::<Vec<String>>();
if !output.is_empty() {
Ok(Value::String {
val: output.join("======================\n\n"),
span: call.head,
}
.into_pipeline_data())
} else {
Err(ShellError::CommandNotFound(span(&[
rest[0].span,
rest[rest.len() - 1].span,
])))
}
}
} else {
let msg = r#"Welcome to Nushell.
Here are some tips to help you get started.
* help -h or help help - show available `help` subcommands and examples
* help commands - list all available commands
* help <name> - display help about a particular command, alias, or module
* help --find <text to search> - search through all help commands table
* help <command name> - display help about a particular command
* help --find <text to search> - search through all of help
Nushell works on the idea of a "pipeline". Pipelines are commands connected with the '|' character.
Each stage in the pipeline works together to load, parse, and display information to you.
@ -82,111 +334,12 @@ Get the processes on your system actively using CPU:
You can also learn more at https://www.nushell.sh/book/"#;
Ok(Value::string(msg, head).into_pipeline_data())
} else if find.is_some() {
help_commands(engine_state, stack, call)
} else {
let result = help_commands(engine_state, stack, call);
let result = if let Err(ShellError::CommandNotFound(_)) = result {
help_aliases(engine_state, stack, call)
} else {
result
};
let result = if let Err(ShellError::AliasNotFound(_)) = result {
help_modules(engine_state, stack, call)
} else {
result
};
if let Err(ShellError::ModuleNotFoundAtRuntime(_, _)) = result {
let rest_spans: Vec<Span> = rest.iter().map(|arg| arg.span).collect();
Err(ShellError::NotFound(span(&rest_spans)))
} else {
result
}
Ok(Value::String {
val: msg.into(),
span: head,
}
.into_pipeline_data())
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "show help for single command, alias, or module",
example: "help match",
result: None,
},
Example {
description: "show help for single sub-command, alias, or module",
example: "help str lpad",
result: None,
},
Example {
description: "search for string in command names, usage and search terms",
example: "help --find char",
result: None,
},
]
}
}
pub fn highlight_search_in_table(
table: Vec<Value>, // list of records
search_string: &str,
searched_cols: &[&str],
string_style: &Style,
) -> Result<Vec<Value>, ShellError> {
let orig_search_string = search_string;
let search_string = search_string.to_lowercase();
let mut matches = vec![];
for record in table {
let (cols, mut vals, record_span) = if let Value::Record { cols, vals, span } = record {
(cols, vals, span)
} else {
return Err(ShellError::NushellFailedSpanned(
"Expected record".to_string(),
format!("got {}", record.get_type()),
record.span()?,
));
};
let has_match = cols.iter().zip(vals.iter_mut()).fold(
Ok(false),
|acc: Result<bool, ShellError>, (col, val)| {
if searched_cols.contains(&col.as_str()) {
if let Value::String { val: s, span } = val {
if s.to_lowercase().contains(&search_string) {
*val = Value::String {
val: highlight_search_string(s, orig_search_string, string_style)?,
span: *span,
};
Ok(true)
} else {
// column does not contain the searched string
acc
}
} else {
// ignore non-string values
acc
}
} else {
// don't search this column
acc
}
},
)?;
if has_match {
matches.push(Value::Record {
cols,
vals,
span: record_span,
});
}
}
Ok(matches)
}
// Highlight the search string using ANSI escape sequences and regular expressions.

View File

@ -1,181 +0,0 @@
use crate::help::highlight_search_in_table;
use nu_color_config::StyleComputer;
use nu_engine::{scope::ScopeData, CallExt};
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
span, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
use std::borrow::Cow;
#[derive(Clone)]
pub struct HelpAliases;
impl Command for HelpAliases {
fn name(&self) -> &str {
"help aliases"
}
fn usage(&self) -> &str {
"Show help on nushell aliases."
}
fn signature(&self) -> Signature {
Signature::build("help aliases")
.category(Category::Core)
.rest(
"rest",
SyntaxShape::String,
"the name of alias to get help on",
)
.named(
"find",
SyntaxShape::String,
"string to find in alias names and usage",
Some('f'),
)
.input_output_types(vec![(Type::Nothing, Type::Table(vec![]))])
.allow_variants_without_examples(true)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "show all aliases",
example: "help aliases",
result: None,
},
Example {
description: "show help for single alias",
example: "help aliases my-alias",
result: None,
},
Example {
description: "search for string in alias names and usages",
example: "help aliases --find my-alias",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
help_aliases(engine_state, stack, call)
}
}
pub fn help_aliases(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
// 🚩The following two-lines are copied from filters/find.rs:
let style_computer = StyleComputer::from_config(engine_state, stack);
// Currently, search results all use the same style.
// Also note that this sample string is passed into user-written code (the closure that may or may not be
// defined for "string").
let string_style = style_computer.compute("string", &Value::string("search result", head));
if let Some(f) = find {
let all_cmds_vec = build_help_aliases(engine_state, stack, head);
let found_cmds_vec =
highlight_search_in_table(all_cmds_vec, &f.item, &["name", "usage"], &string_style)?;
return Ok(found_cmds_vec
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()));
}
if rest.is_empty() {
let found_cmds_vec = build_help_aliases(engine_state, stack, head);
Ok(found_cmds_vec
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()))
} else {
let mut name = String::new();
for r in &rest {
if !name.is_empty() {
name.push(' ');
}
name.push_str(&r.item);
}
let alias_id = if let Some(id) = engine_state.find_alias(name.as_bytes(), &[]) {
id
} else {
return Err(ShellError::AliasNotFound(span(
&rest.iter().map(|r| r.span).collect::<Vec<Span>>(),
)));
};
let alias_expansion = engine_state
.get_alias(alias_id)
.iter()
.map(|span| String::from_utf8_lossy(engine_state.get_span_contents(span)))
.collect::<Vec<Cow<str>>>()
.join(" ");
let alias_usage = engine_state.build_alias_usage(alias_id);
// TODO: merge this into documentation.rs at some point
const G: &str = "\x1b[32m"; // green
const C: &str = "\x1b[36m"; // cyan
const RESET: &str = "\x1b[0m"; // reset
let mut long_desc = String::new();
if let Some((usage, extra_usage)) = alias_usage {
long_desc.push_str(&usage);
long_desc.push_str("\n\n");
if !extra_usage.is_empty() {
long_desc.push_str(&extra_usage);
long_desc.push_str("\n\n");
}
}
long_desc.push_str(&format!("{G}Alias{RESET}: {C}{name}{RESET}"));
long_desc.push_str("\n\n");
long_desc.push_str(&format!("{G}Expansion{RESET}:\n {alias_expansion}"));
let config = engine_state.get_config();
if !config.use_ansi_coloring {
long_desc = nu_utils::strip_ansi_string_likely(long_desc);
}
Ok(Value::String {
val: long_desc,
span: call.head,
}
.into_pipeline_data())
}
}
fn build_help_aliases(engine_state: &EngineState, stack: &Stack, span: Span) -> Vec<Value> {
let mut scope_data = ScopeData::new(engine_state, stack);
scope_data.populate_aliases();
scope_data.collect_aliases(span)
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpAliases;
use crate::test_examples;
test_examples(HelpAliases {})
}
}

View File

@ -1,189 +0,0 @@
use crate::help::highlight_search_in_table;
use nu_color_config::StyleComputer;
use nu_engine::{get_full_help, CallExt};
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
span, Category, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, ShellError,
Signature, Span, Spanned, SyntaxShape, Type, Value,
};
use std::borrow::Borrow;
#[derive(Clone)]
pub struct HelpCommands;
impl Command for HelpCommands {
fn name(&self) -> &str {
"help commands"
}
fn usage(&self) -> &str {
"Show help on nushell commands."
}
fn signature(&self) -> Signature {
Signature::build("help commands")
.category(Category::Core)
.rest(
"rest",
SyntaxShape::String,
"the name of command to get help on",
)
.named(
"find",
SyntaxShape::String,
"string to find in command names, usage, and search terms",
Some('f'),
)
.input_output_types(vec![(Type::Nothing, Type::Table(vec![]))])
.allow_variants_without_examples(true)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
help_commands(engine_state, stack, call)
}
}
pub fn help_commands(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
// 🚩The following two-lines are copied from filters/find.rs:
let style_computer = StyleComputer::from_config(engine_state, stack);
// Currently, search results all use the same style.
// Also note that this sample string is passed into user-written code (the closure that may or may not be
// defined for "string").
let string_style = style_computer.compute("string", &Value::string("search result", head));
if let Some(f) = find {
let all_cmds_vec = build_help_commands(engine_state, head);
let found_cmds_vec = highlight_search_in_table(
all_cmds_vec,
&f.item,
&["name", "usage", "search_terms"],
&string_style,
)?;
return Ok(found_cmds_vec
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()));
}
if rest.is_empty() {
let found_cmds_vec = build_help_commands(engine_state, head);
Ok(found_cmds_vec
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()))
} else {
let mut name = String::new();
for r in &rest {
if !name.is_empty() {
name.push(' ');
}
name.push_str(&r.item);
}
let output = engine_state
.get_signatures_with_examples(false)
.iter()
.filter(|(signature, _, _, _, _)| signature.name == name)
.map(|(signature, examples, _, _, is_parser_keyword)| {
get_full_help(signature, examples, engine_state, stack, *is_parser_keyword)
})
.collect::<Vec<String>>();
if !output.is_empty() {
Ok(Value::String {
val: output.join("======================\n\n"),
span: call.head,
}
.into_pipeline_data())
} else {
Err(ShellError::CommandNotFound(span(&[
rest[0].span,
rest[rest.len() - 1].span,
])))
}
}
}
fn build_help_commands(engine_state: &EngineState, span: Span) -> Vec<Value> {
let commands = engine_state.get_decls_sorted(false);
let mut found_cmds_vec = Vec::new();
for (name_bytes, decl_id) in commands {
let mut cols = vec![];
let mut vals = vec![];
let name = String::from_utf8_lossy(&name_bytes).to_string();
let decl = engine_state.get_decl(decl_id);
let sig = decl.signature().update_from_command(name, decl.borrow());
let signatures = sig.to_string();
let key = sig.name;
let usage = sig.usage;
let search_terms = sig.search_terms;
cols.push("name".into());
vals.push(Value::String { val: key, span });
cols.push("category".into());
vals.push(Value::string(sig.category.to_string(), span));
cols.push("command_type".into());
vals.push(Value::String {
val: format!("{:?}", decl.command_type()).to_lowercase(),
span,
});
cols.push("usage".into());
vals.push(Value::String { val: usage, span });
cols.push("signatures".into());
vals.push(Value::String {
val: if decl.is_parser_keyword() {
"".to_string()
} else {
signatures
},
span,
});
cols.push("search_terms".into());
vals.push(if search_terms.is_empty() {
Value::nothing(span)
} else {
Value::String {
val: search_terms.join(", "),
span,
}
});
found_cmds_vec.push(Value::Record { cols, vals, span });
}
found_cmds_vec
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpCommands;
use crate::test_examples;
test_examples(HelpCommands {})
}
}

View File

@ -1,258 +0,0 @@
use crate::help::highlight_search_in_table;
use nu_color_config::StyleComputer;
use nu_engine::{scope::ScopeData, CallExt};
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
span, AliasId, Category, DeclId, Example, IntoInterruptiblePipelineData, IntoPipelineData,
PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
#[derive(Clone)]
pub struct HelpModules;
impl Command for HelpModules {
fn name(&self) -> &str {
"help modules"
}
fn usage(&self) -> &str {
"Show help on nushell modules."
}
fn extra_usage(&self) -> &str {
r#"When requesting help for a single module, its commands and aliases will be highlighted if they
are also available in the current scope. Commands/aliases that were imported under a different name
(such as with a prefix after `use some-module`) will be highlighted in parentheses."#
}
fn signature(&self) -> Signature {
Signature::build("help modules")
.category(Category::Core)
.rest(
"rest",
SyntaxShape::String,
"the name of module to get help on",
)
.named(
"find",
SyntaxShape::String,
"string to find in module names and usage",
Some('f'),
)
.input_output_types(vec![(Type::Nothing, Type::Table(vec![]))])
.allow_variants_without_examples(true)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "show all modules",
example: "help modules",
result: None,
},
Example {
description: "show help for single module",
example: "help modules my-module",
result: None,
},
Example {
description: "search for string in module names and usages",
example: "help modules --find my-module",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
help_modules(engine_state, stack, call)
}
}
pub fn help_modules(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let find: Option<Spanned<String>> = call.get_flag(engine_state, stack, "find")?;
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
// 🚩The following two-lines are copied from filters/find.rs:
let style_computer = StyleComputer::from_config(engine_state, stack);
// Currently, search results all use the same style.
// Also note that this sample string is passed into user-written code (the closure that may or may not be
// defined for "string").
let string_style = style_computer.compute("string", &Value::string("search result", head));
if let Some(f) = find {
let all_cmds_vec = build_help_modules(engine_state, stack, head);
let found_cmds_vec =
highlight_search_in_table(all_cmds_vec, &f.item, &["name", "usage"], &string_style)?;
return Ok(found_cmds_vec
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()));
}
if rest.is_empty() {
let found_cmds_vec = build_help_modules(engine_state, stack, head);
Ok(found_cmds_vec
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()))
} else {
let mut name = String::new();
for r in &rest {
if !name.is_empty() {
name.push(' ');
}
name.push_str(&r.item);
}
let module_id = if let Some(id) = engine_state.find_module(name.as_bytes(), &[]) {
id
} else {
return Err(ShellError::ModuleNotFoundAtRuntime(
name,
span(&rest.iter().map(|r| r.span).collect::<Vec<Span>>()),
));
};
let module = engine_state.get_module(module_id);
let module_usage = engine_state.build_module_usage(module_id);
// TODO: merge this into documentation.rs at some point
const G: &str = "\x1b[32m"; // green
const C: &str = "\x1b[36m"; // cyan
const CB: &str = "\x1b[1;36m"; // cyan bold
const RESET: &str = "\x1b[0m"; // reset
let mut long_desc = String::new();
if let Some((usage, extra_usage)) = module_usage {
long_desc.push_str(&usage);
long_desc.push_str("\n\n");
if !extra_usage.is_empty() {
long_desc.push_str(&extra_usage);
long_desc.push_str("\n\n");
}
}
long_desc.push_str(&format!("{G}Module{RESET}: {C}{name}{RESET}"));
long_desc.push_str("\n\n");
if !module.decls.is_empty() {
let commands: Vec<(Vec<u8>, DeclId)> = engine_state.get_decls_sorted(false).collect();
let mut module_commands: Vec<(&[u8], DeclId)> = module
.decls
.iter()
.map(|(name, id)| (name.as_ref(), *id))
.collect();
module_commands.sort_by(|a, b| a.0.cmp(b.0));
let commands_str = module_commands
.iter()
.map(|(name_bytes, id)| {
let name = String::from_utf8_lossy(name_bytes);
if let Some((used_name_bytes, _)) =
commands.iter().find(|(_, decl_id)| id == decl_id)
{
if engine_state.find_decl(name.as_bytes(), &[]).is_some() {
format!("{CB}{name}{RESET}")
} else {
let command_name = String::from_utf8_lossy(used_name_bytes);
format!("{name} ({CB}{command_name}{RESET})")
}
} else {
format!("{name}")
}
})
.collect::<Vec<String>>()
.join(", ");
long_desc.push_str(&format!("{G}Exported commands{RESET}:\n {commands_str}"));
long_desc.push_str("\n\n");
}
if !module.aliases.is_empty() {
let aliases: Vec<(Vec<u8>, AliasId)> = engine_state.get_aliases_sorted(false).collect();
let mut module_aliases: Vec<(&[u8], AliasId)> = module
.aliases
.iter()
.map(|(name, id)| (name.as_ref(), *id))
.collect();
module_aliases.sort_by(|a, b| a.0.cmp(b.0));
let aliases_str = module_aliases
.iter()
.map(|(name_bytes, id)| {
let name = String::from_utf8_lossy(name_bytes);
if let Some((used_name_bytes, _)) =
aliases.iter().find(|(_, alias_id)| id == alias_id)
{
if engine_state.find_alias(name.as_bytes(), &[]).is_some() {
format!("{CB}{name}{RESET}")
} else {
let alias_name = String::from_utf8_lossy(used_name_bytes);
format!("{name} ({CB}{alias_name}{RESET})")
}
} else {
format!("{name}")
}
})
.collect::<Vec<String>>()
.join(", ");
long_desc.push_str(&format!("{G}Exported aliases{RESET}:\n {aliases_str}"));
long_desc.push_str("\n\n");
}
if module.env_block.is_some() {
long_desc.push_str(&format!("This module {C}exports{RESET} environment."));
} else {
long_desc.push_str(&format!(
"This module {C}does not export{RESET} environment."
));
}
let config = engine_state.get_config();
if !config.use_ansi_coloring {
long_desc = nu_utils::strip_ansi_string_likely(long_desc);
}
Ok(Value::String {
val: long_desc,
span: call.head,
}
.into_pipeline_data())
}
}
fn build_help_modules(engine_state: &EngineState, stack: &Stack, span: Span) -> Vec<Value> {
let mut scope_data = ScopeData::new(engine_state, stack);
scope_data.populate_modules();
scope_data.collect_modules(span)
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::HelpModules;
use crate::test_examples;
test_examples(HelpModules {})
}
}

View File

@ -1,7 +1,7 @@
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
Category, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Type, Value,
Category, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Value,
};
#[derive(Clone)]
@ -17,10 +17,7 @@ impl Command for HelpOperators {
}
fn signature(&self) -> Signature {
Signature::build("help operators")
.category(Category::Core)
.input_output_types(vec![(Type::Nothing, Type::Table(vec![]))])
.allow_variants_without_examples(true)
Signature::build("help operators").category(Category::Core)
}
fn run(
@ -84,13 +81,6 @@ fn generate_operator_info() -> Vec<OperatorInfo> {
description: "Adds a value to a variable.".into(),
precedence: 10,
},
OperatorInfo {
op_type: "Assignment".into(),
operator: "++=".into(),
name: "AppendAssign".into(),
description: "Appends a list or a value to a variable.".into(),
precedence: 10,
},
OperatorInfo {
op_type: "Assignment".into(),
operator: "-=".into(),
@ -294,6 +284,13 @@ fn generate_operator_info() -> Vec<OperatorInfo> {
description: "Shifts a value right by another.".into(),
precedence: 85,
},
OperatorInfo {
op_type: "Boolean".into(),
operator: "&&".into(),
name: "And".into(),
description: "Deprecated. Checks if two values are true.".into(),
precedence: 50,
},
OperatorInfo {
op_type: "Boolean".into(),
operator: "and".into(),
@ -301,6 +298,13 @@ fn generate_operator_info() -> Vec<OperatorInfo> {
description: "Checks if two values are true.".into(),
precedence: 50,
},
OperatorInfo {
op_type: "Boolean".into(),
operator: "||".into(),
name: "Or".into(),
description: "Deprecated. Checks if either value is true.".into(),
precedence: 40,
},
OperatorInfo {
op_type: "Boolean".into(),
operator: "or".into(),

View File

@ -1,6 +1,8 @@
use nu_protocol::ast::Call;
use nu_protocol::ast::{Call, Expr, Expression};
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, Signature, SyntaxShape, Type};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
#[derive(Clone)]
pub struct Hide;
@ -13,12 +15,7 @@ impl Command for Hide {
fn signature(&self) -> nu_protocol::Signature {
Signature::build("hide")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required("module", SyntaxShape::String, "Module or module file")
.optional(
"members",
SyntaxShape::Any,
"Which members of the module to import",
)
.required("pattern", SyntaxShape::ImportPattern, "import pattern")
.category(Category::Core)
}
@ -39,12 +36,33 @@ This command is a parser keyword. For details, check:
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
Ok(PipelineData::empty())
let env_var_name = if let Some(Expression {
expr: Expr::ImportPattern(pat),
..
}) = call.positional_nth(0)
{
Spanned {
item: String::from_utf8_lossy(&pat.head.name).to_string(),
span: pat.head.span,
}
} else {
return Err(ShellError::GenericError(
"Unexpected import".into(),
"import pattern not supported".into(),
Some(call.head),
None,
Vec::new(),
));
};
stack.remove_env_var(engine_state, &env_var_name.item);
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {
@ -59,6 +77,11 @@ This command is a parser keyword. For details, check:
example: r#"def say-hi [] { echo 'Hi!' }; hide say-hi"#,
result: None,
},
Example {
description: "Hide an environment variable",
example: r#"let-env HZ_ENV_ABC = 1; hide HZ_ENV_ABC; 'HZ_ENV_ABC' in (env).name"#,
result: Some(Value::boolean(false, Span::test_data())),
},
]
}
}

View File

@ -2,8 +2,8 @@ use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
did_you_mean, Category, Example, PipelineData, ShellError, Signature, Spanned, SyntaxShape,
Type, Value,
did_you_mean, Category, Example, PipelineData, ShellError, Signature, Span, Spanned,
SyntaxShape, Type, Value,
};
#[derive(Clone)]
@ -63,14 +63,14 @@ impl Command for HideEnv {
}
}
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Hide an environment variable",
example: r#"let-env HZ_ENV_ABC = 1; hide-env HZ_ENV_ABC; 'HZ_ENV_ABC' in (env).name"#,
result: Some(Value::test_bool(false)),
result: Some(Value::boolean(false, Span::test_data())),
}]
}
}

View File

@ -28,13 +28,7 @@ impl Command for If {
)
.optional(
"else_expression",
SyntaxShape::Keyword(
b"else".to_vec(),
Box::new(SyntaxShape::OneOf(vec![
SyntaxShape::Block,
SyntaxShape::Expression,
])),
),
SyntaxShape::Keyword(b"else".to_vec(), Box::new(SyntaxShape::Expression)),
"expression or block to run if check fails",
)
.category(Category::Core)
@ -108,7 +102,7 @@ impl Command for If {
.map(|res| res.0)
}
} else {
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
}
x => Err(ShellError::CantConvert(

View File

@ -32,7 +32,7 @@ impl Command for Ignore {
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
input.into_value(call.head);
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -70,9 +70,10 @@ impl Command for Let {
)?
.0;
stack.add_var(var_id, rhs.into_value(call.head));
//println!("Adding: {:?} to {}", rhs, var_id);
Ok(PipelineData::empty())
stack.add_var(var_id, rhs.into_value(call.head));
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,8 +1,10 @@
use std::sync::atomic::Ordering;
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Block, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Value,
};
#[derive(Clone)]
@ -19,8 +21,6 @@ impl Command for Loop {
fn signature(&self) -> nu_protocol::Signature {
Signature::build("loop")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.allow_variants_without_examples(true)
.required("block", SyntaxShape::Block, "block to loop")
.category(Category::Core)
}
@ -44,8 +44,10 @@ impl Command for Loop {
let block: Block = call.req(engine_state, stack, 0)?;
loop {
if nu_utils::ctrl_c::was_pressed(&engine_state.ctrlc) {
break;
if let Some(ctrlc) = &engine_state.ctrlc {
if ctrlc.load(Ordering::SeqCst) {
break;
}
}
let block = engine_state.get_block(block.block_id);
@ -53,7 +55,7 @@ impl Command for Loop {
engine_state,
stack,
block,
PipelineData::empty(),
PipelineData::new(call.head),
call.redirect_stdout,
call.redirect_stderr,
) {
@ -67,21 +69,21 @@ impl Command for Loop {
return Err(err);
}
Ok(pipeline) => {
let exit_code = pipeline.print(engine_state, stack, false, false)?;
if exit_code != 0 {
break;
}
pipeline.into_value(call.head);
}
}
}
Ok(PipelineData::empty())
Ok(PipelineData::new(call.head))
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Loop while a condition is true",
example: "mut x = 0; loop { if $x > 10 { break }; $x = $x + 1 }; $x",
result: Some(Value::test_int(11)),
result: Some(Value::Int {
val: 11,
span: Span::test_data(),
}),
}]
}
}

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