From 0dd35cddcd7d8e45f810ebf2de7ac1eb1c8d0042 Mon Sep 17 00:00:00 2001 From: Jack Wright <56345+ayax79@users.noreply.github.com> Date: Tue, 25 Jun 2024 18:26:07 -0700 Subject: [PATCH 01/16] Bumping version to 0.95.1 (#13231) Marks development for hotfix --- Cargo.toml | 40 +++++++++---------- crates/nu-cli/Cargo.toml | 24 +++++------ crates/nu-cmd-base/Cargo.toml | 10 ++--- crates/nu-cmd-extra/Cargo.toml | 22 +++++----- crates/nu-cmd-lang/Cargo.toml | 10 ++--- crates/nu-cmd-plugin/Cargo.toml | 10 ++--- crates/nu-color-config/Cargo.toml | 10 ++--- crates/nu-command/Cargo.toml | 34 ++++++++-------- crates/nu-derive-value/Cargo.toml | 2 +- crates/nu-engine/Cargo.toml | 10 ++--- crates/nu-explore/Cargo.toml | 18 ++++----- crates/nu-glob/Cargo.toml | 2 +- crates/nu-json/Cargo.toml | 4 +- crates/nu-lsp/Cargo.toml | 14 +++---- crates/nu-parser/Cargo.toml | 10 ++--- crates/nu-path/Cargo.toml | 2 +- crates/nu-plugin-core/Cargo.toml | 6 +-- crates/nu-plugin-engine/Cargo.toml | 12 +++--- crates/nu-plugin-protocol/Cargo.toml | 6 +-- crates/nu-plugin-test-support/Cargo.toml | 18 ++++----- crates/nu-plugin/Cargo.toml | 10 ++--- crates/nu-pretty-hex/Cargo.toml | 2 +- crates/nu-protocol/Cargo.toml | 12 +++--- crates/nu-std/Cargo.toml | 8 ++-- crates/nu-system/Cargo.toml | 2 +- crates/nu-table/Cargo.toml | 12 +++--- crates/nu-term-grid/Cargo.toml | 4 +- crates/nu-test-support/Cargo.toml | 8 ++-- crates/nu-utils/Cargo.toml | 2 +- .../src/sample_config/default_config.nu | 2 +- .../nu-utils/src/sample_config/default_env.nu | 2 +- crates/nu_plugin_custom_values/Cargo.toml | 6 +-- crates/nu_plugin_example/Cargo.toml | 10 ++--- crates/nu_plugin_formats/Cargo.toml | 8 ++-- crates/nu_plugin_gstat/Cargo.toml | 6 +-- crates/nu_plugin_inc/Cargo.toml | 6 +-- .../nu_plugin_nu_example.nu | 2 +- crates/nu_plugin_polars/Cargo.toml | 18 ++++----- .../nu_plugin_python_example.py | 2 +- crates/nu_plugin_query/Cargo.toml | 6 +-- crates/nu_plugin_stress_internals/Cargo.toml | 2 +- crates/nuon/Cargo.toml | 8 ++-- 42 files changed, 201 insertions(+), 201 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 696c012b80..3e02e7e066 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ license = "MIT" name = "nu" repository = "https://github.com/nushell/nushell" rust-version = "1.77.2" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -180,22 +180,22 @@ windows = "0.54" winreg = "0.52" [dependencies] -nu-cli = { path = "./crates/nu-cli", version = "0.95.0" } -nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.95.0" } -nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.95.0" } -nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.95.0", optional = true } -nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.95.0" } -nu-command = { path = "./crates/nu-command", version = "0.95.0" } -nu-engine = { path = "./crates/nu-engine", version = "0.95.0" } -nu-explore = { path = "./crates/nu-explore", version = "0.95.0" } -nu-lsp = { path = "./crates/nu-lsp/", version = "0.95.0" } -nu-parser = { path = "./crates/nu-parser", version = "0.95.0" } -nu-path = { path = "./crates/nu-path", version = "0.95.0" } -nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.95.0" } -nu-protocol = { path = "./crates/nu-protocol", version = "0.95.0" } -nu-std = { path = "./crates/nu-std", version = "0.95.0" } -nu-system = { path = "./crates/nu-system", version = "0.95.0" } -nu-utils = { path = "./crates/nu-utils", version = "0.95.0" } +nu-cli = { path = "./crates/nu-cli", version = "0.95.1" } +nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.95.1" } +nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.95.1" } +nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.95.1", optional = true } +nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.95.1" } +nu-command = { path = "./crates/nu-command", version = "0.95.1" } +nu-engine = { path = "./crates/nu-engine", version = "0.95.1" } +nu-explore = { path = "./crates/nu-explore", version = "0.95.1" } +nu-lsp = { path = "./crates/nu-lsp/", version = "0.95.1" } +nu-parser = { path = "./crates/nu-parser", version = "0.95.1" } +nu-path = { path = "./crates/nu-path", version = "0.95.1" } +nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.95.1" } +nu-protocol = { path = "./crates/nu-protocol", version = "0.95.1" } +nu-std = { path = "./crates/nu-std", version = "0.95.1" } +nu-system = { path = "./crates/nu-system", version = "0.95.1" } +nu-utils = { path = "./crates/nu-utils", version = "0.95.1" } reedline = { workspace = true, features = ["bashisms", "sqlite"] } @@ -225,9 +225,9 @@ nix = { workspace = true, default-features = false, features = [ ] } [dev-dependencies] -nu-test-support = { path = "./crates/nu-test-support", version = "0.95.0" } -nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.95.0" } -nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.95.0" } +nu-test-support = { path = "./crates/nu-test-support", version = "0.95.1" } +nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.95.1" } +nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.95.1" } assert_cmd = "2.0" dirs-next = { workspace = true } tango-bench = "0.5" diff --git a/crates/nu-cli/Cargo.toml b/crates/nu-cli/Cargo.toml index 8e7c7b5535..2ed504d502 100644 --- a/crates/nu-cli/Cargo.toml +++ b/crates/nu-cli/Cargo.toml @@ -5,27 +5,27 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cli" edition = "2021" license = "MIT" name = "nu-cli" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dev-dependencies] -nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.0" } -nu-command = { path = "../nu-command", version = "0.95.0" } -nu-test-support = { path = "../nu-test-support", version = "0.95.0" } +nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.1" } +nu-command = { path = "../nu-command", version = "0.95.1" } +nu-test-support = { path = "../nu-test-support", version = "0.95.1" } rstest = { workspace = true, default-features = false } tempfile = { workspace = true } [dependencies] -nu-cmd-base = { path = "../nu-cmd-base", version = "0.95.0" } -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-path = { path = "../nu-path", version = "0.95.0" } -nu-parser = { path = "../nu-parser", version = "0.95.0" } -nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.95.0", optional = true } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-utils = { path = "../nu-utils", version = "0.95.0" } -nu-color-config = { path = "../nu-color-config", version = "0.95.0" } +nu-cmd-base = { path = "../nu-cmd-base", version = "0.95.1" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-path = { path = "../nu-path", version = "0.95.1" } +nu-parser = { path = "../nu-parser", version = "0.95.1" } +nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.95.1", optional = true } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } +nu-color-config = { path = "../nu-color-config", version = "0.95.1" } nu-ansi-term = { workspace = true } reedline = { workspace = true, features = ["bashisms", "sqlite"] } diff --git a/crates/nu-cmd-base/Cargo.toml b/crates/nu-cmd-base/Cargo.toml index 773ee05414..2fe8610f49 100644 --- a/crates/nu-cmd-base/Cargo.toml +++ b/crates/nu-cmd-base/Cargo.toml @@ -5,15 +5,15 @@ edition = "2021" license = "MIT" name = "nu-cmd-base" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-base" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-parser = { path = "../nu-parser", version = "0.95.0" } -nu-path = { path = "../nu-path", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-parser = { path = "../nu-parser", version = "0.95.1" } +nu-path = { path = "../nu-path", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } indexmap = { workspace = true } miette = { workspace = true } diff --git a/crates/nu-cmd-extra/Cargo.toml b/crates/nu-cmd-extra/Cargo.toml index 30c94420a3..8609adb44c 100644 --- a/crates/nu-cmd-extra/Cargo.toml +++ b/crates/nu-cmd-extra/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" license = "MIT" name = "nu-cmd-extra" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-extra" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -13,13 +13,13 @@ version = "0.95.0" bench = false [dependencies] -nu-cmd-base = { path = "../nu-cmd-base", version = "0.95.0" } -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-json = { version = "0.95.0", path = "../nu-json" } -nu-parser = { path = "../nu-parser", version = "0.95.0" } -nu-pretty-hex = { version = "0.95.0", path = "../nu-pretty-hex" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-utils = { path = "../nu-utils", version = "0.95.0" } +nu-cmd-base = { path = "../nu-cmd-base", version = "0.95.1" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-json = { version = "0.95.1", path = "../nu-json" } +nu-parser = { path = "../nu-parser", version = "0.95.1" } +nu-pretty-hex = { version = "0.95.1", path = "../nu-pretty-hex" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } # Potential dependencies for extras heck = { workspace = true } @@ -33,6 +33,6 @@ v_htmlescape = { workspace = true } itertools = { workspace = true } [dev-dependencies] -nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.0" } -nu-command = { path = "../nu-command", version = "0.95.0" } -nu-test-support = { path = "../nu-test-support", version = "0.95.0" } \ No newline at end of file +nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.1" } +nu-command = { path = "../nu-command", version = "0.95.1" } +nu-test-support = { path = "../nu-test-support", version = "0.95.1" } \ No newline at end of file diff --git a/crates/nu-cmd-lang/Cargo.toml b/crates/nu-cmd-lang/Cargo.toml index 6db0d4c096..262248e6d9 100644 --- a/crates/nu-cmd-lang/Cargo.toml +++ b/crates/nu-cmd-lang/Cargo.toml @@ -6,16 +6,16 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-lang" edition = "2021" license = "MIT" name = "nu-cmd-lang" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-parser = { path = "../nu-parser", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-utils = { path = "../nu-utils", version = "0.95.0" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-parser = { path = "../nu-parser", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } itertools = { workspace = true } shadow-rs = { version = "0.28", default-features = false } diff --git a/crates/nu-cmd-plugin/Cargo.toml b/crates/nu-cmd-plugin/Cargo.toml index f6eccb753e..7d26fe5ddd 100644 --- a/crates/nu-cmd-plugin/Cargo.toml +++ b/crates/nu-cmd-plugin/Cargo.toml @@ -5,15 +5,15 @@ edition = "2021" license = "MIT" name = "nu-cmd-plugin" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-plugin" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-path = { path = "../nu-path", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0", features = ["plugin"] } -nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.95.0" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-path = { path = "../nu-path", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1", features = ["plugin"] } +nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.95.1" } itertools = { workspace = true } diff --git a/crates/nu-color-config/Cargo.toml b/crates/nu-color-config/Cargo.toml index 34f15cd74f..23af09432c 100644 --- a/crates/nu-color-config/Cargo.toml +++ b/crates/nu-color-config/Cargo.toml @@ -5,18 +5,18 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-color-confi edition = "2021" license = "MIT" name = "nu-color-config" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-json = { path = "../nu-json", version = "0.95.0" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-json = { path = "../nu-json", version = "0.95.1" } nu-ansi-term = { workspace = true } serde = { workspace = true, features = ["derive"] } [dev-dependencies] -nu-test-support = { path = "../nu-test-support", version = "0.95.0" } \ No newline at end of file +nu-test-support = { path = "../nu-test-support", version = "0.95.1" } \ No newline at end of file diff --git a/crates/nu-command/Cargo.toml b/crates/nu-command/Cargo.toml index 355232b938..474742ae0a 100644 --- a/crates/nu-command/Cargo.toml +++ b/crates/nu-command/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" license = "MIT" name = "nu-command" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-command" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -13,21 +13,21 @@ version = "0.95.0" bench = false [dependencies] -nu-cmd-base = { path = "../nu-cmd-base", version = "0.95.0" } -nu-color-config = { path = "../nu-color-config", version = "0.95.0" } -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-glob = { path = "../nu-glob", version = "0.95.0" } -nu-json = { path = "../nu-json", version = "0.95.0" } -nu-parser = { path = "../nu-parser", version = "0.95.0" } -nu-path = { path = "../nu-path", version = "0.95.0" } -nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-system = { path = "../nu-system", version = "0.95.0" } -nu-table = { path = "../nu-table", version = "0.95.0" } -nu-term-grid = { path = "../nu-term-grid", version = "0.95.0" } -nu-utils = { path = "../nu-utils", version = "0.95.0" } +nu-cmd-base = { path = "../nu-cmd-base", version = "0.95.1" } +nu-color-config = { path = "../nu-color-config", version = "0.95.1" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-glob = { path = "../nu-glob", version = "0.95.1" } +nu-json = { path = "../nu-json", version = "0.95.1" } +nu-parser = { path = "../nu-parser", version = "0.95.1" } +nu-path = { path = "../nu-path", version = "0.95.1" } +nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-system = { path = "../nu-system", version = "0.95.1" } +nu-table = { path = "../nu-table", version = "0.95.1" } +nu-term-grid = { path = "../nu-term-grid", version = "0.95.1" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } nu-ansi-term = { workspace = true } -nuon = { path = "../nuon", version = "0.95.0" } +nuon = { path = "../nuon", version = "0.95.1" } alphanumeric-sort = { workspace = true } base64 = { workspace = true } @@ -136,8 +136,8 @@ sqlite = ["rusqlite"] trash-support = ["trash"] [dev-dependencies] -nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.0" } -nu-test-support = { path = "../nu-test-support", version = "0.95.0" } +nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.1" } +nu-test-support = { path = "../nu-test-support", version = "0.95.1" } dirs-next = { workspace = true } mockito = { workspace = true, default-features = false } diff --git a/crates/nu-derive-value/Cargo.toml b/crates/nu-derive-value/Cargo.toml index 37698ccaeb..50ca5d2407 100644 --- a/crates/nu-derive-value/Cargo.toml +++ b/crates/nu-derive-value/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" license = "MIT" name = "nu-derive-value" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-derive-value" -version = "0.95.0" +version = "0.95.1" [lib] proc-macro = true diff --git a/crates/nu-engine/Cargo.toml b/crates/nu-engine/Cargo.toml index 7c815d4c72..3e6c3f787b 100644 --- a/crates/nu-engine/Cargo.toml +++ b/crates/nu-engine/Cargo.toml @@ -5,16 +5,16 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-engine" edition = "2021" license = "MIT" name = "nu-engine" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-protocol = { path = "../nu-protocol", features = ["plugin"], version = "0.95.0" } -nu-path = { path = "../nu-path", version = "0.95.0" } -nu-glob = { path = "../nu-glob", version = "0.95.0" } -nu-utils = { path = "../nu-utils", version = "0.95.0" } +nu-protocol = { path = "../nu-protocol", features = ["plugin"], version = "0.95.1" } +nu-path = { path = "../nu-path", version = "0.95.1" } +nu-glob = { path = "../nu-glob", version = "0.95.1" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } [features] plugin = [] \ No newline at end of file diff --git a/crates/nu-explore/Cargo.toml b/crates/nu-explore/Cargo.toml index ac0fe732da..6d0816ee3e 100644 --- a/crates/nu-explore/Cargo.toml +++ b/crates/nu-explore/Cargo.toml @@ -5,21 +5,21 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-explore" edition = "2021" license = "MIT" name = "nu-explore" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-parser = { path = "../nu-parser", version = "0.95.0" } -nu-color-config = { path = "../nu-color-config", version = "0.95.0" } -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-table = { path = "../nu-table", version = "0.95.0" } -nu-json = { path = "../nu-json", version = "0.95.0" } -nu-utils = { path = "../nu-utils", version = "0.95.0" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-parser = { path = "../nu-parser", version = "0.95.1" } +nu-color-config = { path = "../nu-color-config", version = "0.95.1" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-table = { path = "../nu-table", version = "0.95.1" } +nu-json = { path = "../nu-json", version = "0.95.1" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } nu-ansi-term = { workspace = true } -nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.95.0" } +nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.95.1" } anyhow = { workspace = true } log = { workspace = true } diff --git a/crates/nu-glob/Cargo.toml b/crates/nu-glob/Cargo.toml index b1386d1f7b..932958910c 100644 --- a/crates/nu-glob/Cargo.toml +++ b/crates/nu-glob/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "nu-glob" -version = "0.95.0" +version = "0.95.1" authors = ["The Nushell Project Developers", "The Rust Project Developers"] license = "MIT/Apache-2.0" description = """ diff --git a/crates/nu-json/Cargo.toml b/crates/nu-json/Cargo.toml index 27db574785..04c39bdac5 100644 --- a/crates/nu-json/Cargo.toml +++ b/crates/nu-json/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-json" edition = "2021" license = "MIT" name = "nu-json" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -23,5 +23,5 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] -# nu-path = { path="../nu-path", version = "0.95.0" } +# nu-path = { path="../nu-path", version = "0.95.1" } # serde_json = "1.0" \ No newline at end of file diff --git a/crates/nu-lsp/Cargo.toml b/crates/nu-lsp/Cargo.toml index 2384d46116..0f9ef01e69 100644 --- a/crates/nu-lsp/Cargo.toml +++ b/crates/nu-lsp/Cargo.toml @@ -3,14 +3,14 @@ authors = ["The Nushell Project Developers"] description = "Nushell's integrated LSP server" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-lsp" name = "nu-lsp" -version = "0.95.0" +version = "0.95.1" edition = "2021" license = "MIT" [dependencies] -nu-cli = { path = "../nu-cli", version = "0.95.0" } -nu-parser = { path = "../nu-parser", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } +nu-cli = { path = "../nu-cli", version = "0.95.1" } +nu-parser = { path = "../nu-parser", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } reedline = { workspace = true } @@ -23,8 +23,8 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] -nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.0" } -nu-command = { path = "../nu-command", version = "0.95.0" } -nu-test-support = { path = "../nu-test-support", version = "0.95.0" } +nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.1" } +nu-command = { path = "../nu-command", version = "0.95.1" } +nu-test-support = { path = "../nu-test-support", version = "0.95.1" } assert-json-diff = "2.0" \ No newline at end of file diff --git a/crates/nu-parser/Cargo.toml b/crates/nu-parser/Cargo.toml index 5ca1a59d0c..b06e81387d 100644 --- a/crates/nu-parser/Cargo.toml +++ b/crates/nu-parser/Cargo.toml @@ -5,17 +5,17 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-parser" edition = "2021" license = "MIT" name = "nu-parser" -version = "0.95.0" +version = "0.95.1" exclude = ["/fuzz"] [lib] bench = false [dependencies] -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-path = { path = "../nu-path", version = "0.95.0" } -nu-plugin-engine = { path = "../nu-plugin-engine", optional = true, version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-path = { path = "../nu-path", version = "0.95.1" } +nu-plugin-engine = { path = "../nu-plugin-engine", optional = true, version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } bytesize = { workspace = true } chrono = { default-features = false, features = ['std'], workspace = true } diff --git a/crates/nu-path/Cargo.toml b/crates/nu-path/Cargo.toml index cf716b4571..dc2f870a9d 100644 --- a/crates/nu-path/Cargo.toml +++ b/crates/nu-path/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-path" edition = "2021" license = "MIT" name = "nu-path" -version = "0.95.0" +version = "0.95.1" exclude = ["/fuzz"] [lib] diff --git a/crates/nu-plugin-core/Cargo.toml b/crates/nu-plugin-core/Cargo.toml index 3e56d0f8e1..48aee13276 100644 --- a/crates/nu-plugin-core/Cargo.toml +++ b/crates/nu-plugin-core/Cargo.toml @@ -5,14 +5,14 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-plugin-core edition = "2021" license = "MIT" name = "nu-plugin-core" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-plugin-protocol = { path = "../nu-plugin-protocol", version = "0.95.0", default-features = false } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-plugin-protocol = { path = "../nu-plugin-protocol", version = "0.95.1", default-features = false } rmp-serde = { workspace = true } serde = { workspace = true } diff --git a/crates/nu-plugin-engine/Cargo.toml b/crates/nu-plugin-engine/Cargo.toml index 5de92d1560..f86c1ae703 100644 --- a/crates/nu-plugin-engine/Cargo.toml +++ b/crates/nu-plugin-engine/Cargo.toml @@ -5,17 +5,17 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-plugin-engi edition = "2021" license = "MIT" name = "nu-plugin-engine" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-system = { path = "../nu-system", version = "0.95.0" } -nu-plugin-protocol = { path = "../nu-plugin-protocol", version = "0.95.0" } -nu-plugin-core = { path = "../nu-plugin-core", version = "0.95.0", default-features = false } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-system = { path = "../nu-system", version = "0.95.1" } +nu-plugin-protocol = { path = "../nu-plugin-protocol", version = "0.95.1" } +nu-plugin-core = { path = "../nu-plugin-core", version = "0.95.1", default-features = false } serde = { workspace = true } log = { workspace = true } diff --git a/crates/nu-plugin-protocol/Cargo.toml b/crates/nu-plugin-protocol/Cargo.toml index 23bd524734..939f164786 100644 --- a/crates/nu-plugin-protocol/Cargo.toml +++ b/crates/nu-plugin-protocol/Cargo.toml @@ -5,14 +5,14 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-plugin-prot edition = "2021" license = "MIT" name = "nu-plugin-protocol" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-protocol = { path = "../nu-protocol", version = "0.95.0", features = ["plugin"] } -nu-utils = { path = "../nu-utils", version = "0.95.0" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1", features = ["plugin"] } +nu-utils = { path = "../nu-utils", version = "0.95.1" } bincode = "1.3" serde = { workspace = true, features = ["derive"] } diff --git a/crates/nu-plugin-test-support/Cargo.toml b/crates/nu-plugin-test-support/Cargo.toml index b7220da898..efc76c3b93 100644 --- a/crates/nu-plugin-test-support/Cargo.toml +++ b/crates/nu-plugin-test-support/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "nu-plugin-test-support" -version = "0.95.0" +version = "0.95.1" edition = "2021" license = "MIT" description = "Testing support for Nushell plugins" @@ -12,14 +12,14 @@ bench = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -nu-engine = { path = "../nu-engine", version = "0.95.0", features = ["plugin"] } -nu-protocol = { path = "../nu-protocol", version = "0.95.0", features = ["plugin"] } -nu-parser = { path = "../nu-parser", version = "0.95.0", features = ["plugin"] } -nu-plugin = { path = "../nu-plugin", version = "0.95.0" } -nu-plugin-core = { path = "../nu-plugin-core", version = "0.95.0" } -nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.95.0" } -nu-plugin-protocol = { path = "../nu-plugin-protocol", version = "0.95.0" } -nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.0" } +nu-engine = { path = "../nu-engine", version = "0.95.1", features = ["plugin"] } +nu-protocol = { path = "../nu-protocol", version = "0.95.1", features = ["plugin"] } +nu-parser = { path = "../nu-parser", version = "0.95.1", features = ["plugin"] } +nu-plugin = { path = "../nu-plugin", version = "0.95.1" } +nu-plugin-core = { path = "../nu-plugin-core", version = "0.95.1" } +nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.95.1" } +nu-plugin-protocol = { path = "../nu-plugin-protocol", version = "0.95.1" } +nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.1" } nu-ansi-term = { workspace = true } similar = "2.5" diff --git a/crates/nu-plugin/Cargo.toml b/crates/nu-plugin/Cargo.toml index 6f843cf264..a3b4455d15 100644 --- a/crates/nu-plugin/Cargo.toml +++ b/crates/nu-plugin/Cargo.toml @@ -5,16 +5,16 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-plugin" edition = "2021" license = "MIT" name = "nu-plugin" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-plugin-protocol = { path = "../nu-plugin-protocol", version = "0.95.0" } -nu-plugin-core = { path = "../nu-plugin-core", version = "0.95.0", default-features = false } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-plugin-protocol = { path = "../nu-plugin-protocol", version = "0.95.1" } +nu-plugin-core = { path = "../nu-plugin-core", version = "0.95.1", default-features = false } log = { workspace = true } thiserror = "1.0" diff --git a/crates/nu-pretty-hex/Cargo.toml b/crates/nu-pretty-hex/Cargo.toml index 2b6a683295..cd3c3502a4 100644 --- a/crates/nu-pretty-hex/Cargo.toml +++ b/crates/nu-pretty-hex/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-pretty-hex" edition = "2021" license = "MIT" name = "nu-pretty-hex" -version = "0.95.0" +version = "0.95.1" [lib] doctest = false diff --git a/crates/nu-protocol/Cargo.toml b/crates/nu-protocol/Cargo.toml index 73637cf292..ee0f5a8221 100644 --- a/crates/nu-protocol/Cargo.toml +++ b/crates/nu-protocol/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-protocol" edition = "2021" license = "MIT" name = "nu-protocol" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -13,10 +13,10 @@ version = "0.95.0" bench = false [dependencies] -nu-utils = { path = "../nu-utils", version = "0.95.0" } -nu-path = { path = "../nu-path", version = "0.95.0" } -nu-system = { path = "../nu-system", version = "0.95.0" } -nu-derive-value = { path = "../nu-derive-value", version = "0.95.0" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } +nu-path = { path = "../nu-path", version = "0.95.1" } +nu-system = { path = "../nu-system", version = "0.95.1" } +nu-derive-value = { path = "../nu-derive-value", version = "0.95.1" } brotli = { workspace = true, optional = true } byte-unit = { version = "5.1", features = [ "serde" ] } @@ -47,7 +47,7 @@ plugin = [ serde_json = { workspace = true } strum = "0.26" strum_macros = "0.26" -nu-test-support = { path = "../nu-test-support", version = "0.95.0" } +nu-test-support = { path = "../nu-test-support", version = "0.95.1" } pretty_assertions = { workspace = true } rstest = { workspace = true } tempfile = { workspace = true } diff --git a/crates/nu-std/Cargo.toml b/crates/nu-std/Cargo.toml index 2617f4656d..9ee4113e96 100644 --- a/crates/nu-std/Cargo.toml +++ b/crates/nu-std/Cargo.toml @@ -5,12 +5,12 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-std" edition = "2021" license = "MIT" name = "nu-std" -version = "0.95.0" +version = "0.95.1" [dependencies] -nu-parser = { version = "0.95.0", path = "../nu-parser" } -nu-protocol = { version = "0.95.0", path = "../nu-protocol" } -nu-engine = { version = "0.95.0", path = "../nu-engine" } +nu-parser = { version = "0.95.1", path = "../nu-parser" } +nu-protocol = { version = "0.95.1", path = "../nu-protocol" } +nu-engine = { version = "0.95.1", path = "../nu-engine" } miette = { workspace = true, features = ["fancy-no-backtrace"] } log = "0.4" \ No newline at end of file diff --git a/crates/nu-system/Cargo.toml b/crates/nu-system/Cargo.toml index b9b23af6c3..19ab1259fb 100644 --- a/crates/nu-system/Cargo.toml +++ b/crates/nu-system/Cargo.toml @@ -3,7 +3,7 @@ authors = ["The Nushell Project Developers", "procs creators"] description = "Nushell system querying" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-system" name = "nu-system" -version = "0.95.0" +version = "0.95.1" edition = "2021" license = "MIT" diff --git a/crates/nu-table/Cargo.toml b/crates/nu-table/Cargo.toml index dcc4c294d6..9f00c4d1fd 100644 --- a/crates/nu-table/Cargo.toml +++ b/crates/nu-table/Cargo.toml @@ -5,20 +5,20 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-table" edition = "2021" license = "MIT" name = "nu-table" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-utils = { path = "../nu-utils", version = "0.95.0" } -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-color-config = { path = "../nu-color-config", version = "0.95.0" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-color-config = { path = "../nu-color-config", version = "0.95.1" } nu-ansi-term = { workspace = true } once_cell = { workspace = true } fancy-regex = { workspace = true } tabled = { workspace = true, features = ["color"], default-features = false } [dev-dependencies] -# nu-test-support = { path="../nu-test-support", version = "0.95.0" } \ No newline at end of file +# nu-test-support = { path="../nu-test-support", version = "0.95.1" } \ No newline at end of file diff --git a/crates/nu-term-grid/Cargo.toml b/crates/nu-term-grid/Cargo.toml index a577e6cb24..0229f1f0f0 100644 --- a/crates/nu-term-grid/Cargo.toml +++ b/crates/nu-term-grid/Cargo.toml @@ -5,12 +5,12 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-term-grid" edition = "2021" license = "MIT" name = "nu-term-grid" -version = "0.95.0" +version = "0.95.1" [lib] bench = false [dependencies] -nu-utils = { path = "../nu-utils", version = "0.95.0" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } unicode-width = { workspace = true } \ No newline at end of file diff --git a/crates/nu-test-support/Cargo.toml b/crates/nu-test-support/Cargo.toml index 769ae44d00..1b5f5df7ba 100644 --- a/crates/nu-test-support/Cargo.toml +++ b/crates/nu-test-support/Cargo.toml @@ -5,16 +5,16 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-test-suppor edition = "2021" license = "MIT" name = "nu-test-support" -version = "0.95.0" +version = "0.95.1" [lib] doctest = false bench = false [dependencies] -nu-path = { path = "../nu-path", version = "0.95.0" } -nu-glob = { path = "../nu-glob", version = "0.95.0" } -nu-utils = { path = "../nu-utils", version = "0.95.0" } +nu-path = { path = "../nu-path", version = "0.95.1" } +nu-glob = { path = "../nu-glob", version = "0.95.1" } +nu-utils = { path = "../nu-utils", version = "0.95.1" } num-format = { workspace = true } which = { workspace = true } diff --git a/crates/nu-utils/Cargo.toml b/crates/nu-utils/Cargo.toml index 54821d0252..60b4cb21aa 100644 --- a/crates/nu-utils/Cargo.toml +++ b/crates/nu-utils/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" license = "MIT" name = "nu-utils" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-utils" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [[bin]] diff --git a/crates/nu-utils/src/sample_config/default_config.nu b/crates/nu-utils/src/sample_config/default_config.nu index 0980b487e2..5856e385c4 100644 --- a/crates/nu-utils/src/sample_config/default_config.nu +++ b/crates/nu-utils/src/sample_config/default_config.nu @@ -1,6 +1,6 @@ # Nushell Config File # -# version = "0.95.0" +# version = "0.95.1" # For more information on defining custom themes, see # https://www.nushell.sh/book/coloring_and_theming.html diff --git a/crates/nu-utils/src/sample_config/default_env.nu b/crates/nu-utils/src/sample_config/default_env.nu index e5c17e40de..a686f6f99a 100644 --- a/crates/nu-utils/src/sample_config/default_env.nu +++ b/crates/nu-utils/src/sample_config/default_env.nu @@ -1,6 +1,6 @@ # Nushell Environment Config File # -# version = "0.95.0" +# version = "0.95.1" def create_left_prompt [] { let dir = match (do --ignore-shell-errors { $env.PWD | path relative-to $nu.home-path }) { diff --git a/crates/nu_plugin_custom_values/Cargo.toml b/crates/nu_plugin_custom_values/Cargo.toml index 0b8c899bb3..e5f8951429 100644 --- a/crates/nu_plugin_custom_values/Cargo.toml +++ b/crates/nu_plugin_custom_values/Cargo.toml @@ -10,10 +10,10 @@ name = "nu_plugin_custom_values" bench = false [dependencies] -nu-plugin = { path = "../nu-plugin", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0", features = ["plugin"] } +nu-plugin = { path = "../nu-plugin", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1", features = ["plugin"] } serde = { workspace = true, default-features = false } typetag = "0.2" [dev-dependencies] -nu-plugin-test-support = { path = "../nu-plugin-test-support", version = "0.95.0" } \ No newline at end of file +nu-plugin-test-support = { path = "../nu-plugin-test-support", version = "0.95.1" } \ No newline at end of file diff --git a/crates/nu_plugin_example/Cargo.toml b/crates/nu_plugin_example/Cargo.toml index 9e5dc917f5..08ba3e1566 100644 --- a/crates/nu_plugin_example/Cargo.toml +++ b/crates/nu_plugin_example/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu_plugin_exam edition = "2021" license = "MIT" name = "nu_plugin_example" -version = "0.95.0" +version = "0.95.1" [[bin]] name = "nu_plugin_example" @@ -15,9 +15,9 @@ bench = false bench = false [dependencies] -nu-plugin = { path = "../nu-plugin", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0", features = ["plugin"] } +nu-plugin = { path = "../nu-plugin", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1", features = ["plugin"] } [dev-dependencies] -nu-plugin-test-support = { path = "../nu-plugin-test-support", version = "0.95.0" } -nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.0" } \ No newline at end of file +nu-plugin-test-support = { path = "../nu-plugin-test-support", version = "0.95.1" } +nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.1" } \ No newline at end of file diff --git a/crates/nu_plugin_formats/Cargo.toml b/crates/nu_plugin_formats/Cargo.toml index a2c198bcb0..29e8953f24 100644 --- a/crates/nu_plugin_formats/Cargo.toml +++ b/crates/nu_plugin_formats/Cargo.toml @@ -5,12 +5,12 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu_plugin_form edition = "2021" license = "MIT" name = "nu_plugin_formats" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -nu-plugin = { path = "../nu-plugin", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0", features = ["plugin"] } +nu-plugin = { path = "../nu-plugin", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1", features = ["plugin"] } indexmap = { workspace = true } eml-parser = "0.1" @@ -18,4 +18,4 @@ ical = "0.11" rust-ini = "0.21.0" [dev-dependencies] -nu-plugin-test-support = { path = "../nu-plugin-test-support", version = "0.95.0" } \ No newline at end of file +nu-plugin-test-support = { path = "../nu-plugin-test-support", version = "0.95.1" } \ No newline at end of file diff --git a/crates/nu_plugin_gstat/Cargo.toml b/crates/nu_plugin_gstat/Cargo.toml index 15b601007a..da1c13a88e 100644 --- a/crates/nu_plugin_gstat/Cargo.toml +++ b/crates/nu_plugin_gstat/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu_plugin_gsta edition = "2021" license = "MIT" name = "nu_plugin_gstat" -version = "0.95.0" +version = "0.95.1" [lib] doctest = false @@ -16,7 +16,7 @@ name = "nu_plugin_gstat" bench = false [dependencies] -nu-plugin = { path = "../nu-plugin", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } +nu-plugin = { path = "../nu-plugin", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } git2 = "0.19" \ No newline at end of file diff --git a/crates/nu_plugin_inc/Cargo.toml b/crates/nu_plugin_inc/Cargo.toml index 9f2b0e1122..0479a47843 100644 --- a/crates/nu_plugin_inc/Cargo.toml +++ b/crates/nu_plugin_inc/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu_plugin_inc" edition = "2021" license = "MIT" name = "nu_plugin_inc" -version = "0.95.0" +version = "0.95.1" [lib] doctest = false @@ -16,7 +16,7 @@ name = "nu_plugin_inc" bench = false [dependencies] -nu-plugin = { path = "../nu-plugin", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0", features = ["plugin"] } +nu-plugin = { path = "../nu-plugin", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1", features = ["plugin"] } semver = "1.0" \ No newline at end of file diff --git a/crates/nu_plugin_nu_example/nu_plugin_nu_example.nu b/crates/nu_plugin_nu_example/nu_plugin_nu_example.nu index 1fcf6d8eb4..d19cd36c14 100755 --- a/crates/nu_plugin_nu_example/nu_plugin_nu_example.nu +++ b/crates/nu_plugin_nu_example/nu_plugin_nu_example.nu @@ -6,7 +6,7 @@ # it also allows us to test the plugin interface with something manually implemented in a scripting # language without adding any extra dependencies to our tests. -const NUSHELL_VERSION = "0.95.0" +const NUSHELL_VERSION = "0.95.1" const PLUGIN_VERSION = "0.1.0" # bump if you change commands! def main [--stdio] { diff --git a/crates/nu_plugin_polars/Cargo.toml b/crates/nu_plugin_polars/Cargo.toml index e5e92822e0..77bb84e988 100644 --- a/crates/nu_plugin_polars/Cargo.toml +++ b/crates/nu_plugin_polars/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" license = "MIT" name = "nu_plugin_polars" repository = "https://github.com/nushell/nushell/tree/main/crates/nu_plugin_polars" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -17,9 +17,9 @@ bench = false bench = false [dependencies] -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-plugin = { path = "../nu-plugin", version = "0.95.0" } -nu-path = { path = "../nu-path", version = "0.95.0" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-plugin = { path = "../nu-plugin", version = "0.95.1" } +nu-path = { path = "../nu-path", version = "0.95.1" } # Potential dependencies for extras chrono = { workspace = true, features = ["std", "unstable-locales"], default-features = false } @@ -73,9 +73,9 @@ optional = false version = "0.40" [dev-dependencies] -nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.0" } -nu-engine = { path = "../nu-engine", version = "0.95.0" } -nu-parser = { path = "../nu-parser", version = "0.95.0" } -nu-command = { path = "../nu-command", version = "0.95.0" } -nu-plugin-test-support = { path = "../nu-plugin-test-support", version = "0.95.0" } +nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.95.1" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } +nu-parser = { path = "../nu-parser", version = "0.95.1" } +nu-command = { path = "../nu-command", version = "0.95.1" } +nu-plugin-test-support = { path = "../nu-plugin-test-support", version = "0.95.1" } tempfile.workspace = true \ No newline at end of file diff --git a/crates/nu_plugin_python/nu_plugin_python_example.py b/crates/nu_plugin_python/nu_plugin_python_example.py index 14cd28a713..34e54fea71 100755 --- a/crates/nu_plugin_python/nu_plugin_python_example.py +++ b/crates/nu_plugin_python/nu_plugin_python_example.py @@ -27,7 +27,7 @@ import sys import json -NUSHELL_VERSION = "0.95.0" +NUSHELL_VERSION = "0.95.1" PLUGIN_VERSION = "0.1.0" # bump if you change commands! diff --git a/crates/nu_plugin_query/Cargo.toml b/crates/nu_plugin_query/Cargo.toml index d044aeac42..4a54e9bf60 100644 --- a/crates/nu_plugin_query/Cargo.toml +++ b/crates/nu_plugin_query/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu_plugin_quer edition = "2021" license = "MIT" name = "nu_plugin_query" -version = "0.95.0" +version = "0.95.1" [lib] doctest = false @@ -16,8 +16,8 @@ name = "nu_plugin_query" bench = false [dependencies] -nu-plugin = { path = "../nu-plugin", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } +nu-plugin = { path = "../nu-plugin", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } gjson = "0.8" scraper = { default-features = false, version = "0.19" } diff --git a/crates/nu_plugin_stress_internals/Cargo.toml b/crates/nu_plugin_stress_internals/Cargo.toml index e4e7f88403..2a53eb6749 100644 --- a/crates/nu_plugin_stress_internals/Cargo.toml +++ b/crates/nu_plugin_stress_internals/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu_plugin_stre edition = "2021" license = "MIT" name = "nu_plugin_stress_internals" -version = "0.95.0" +version = "0.95.1" [[bin]] name = "nu_plugin_stress_internals" diff --git a/crates/nuon/Cargo.toml b/crates/nuon/Cargo.toml index f977598450..bbb2dfe73c 100644 --- a/crates/nuon/Cargo.toml +++ b/crates/nuon/Cargo.toml @@ -5,14 +5,14 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nuon" edition = "2021" license = "MIT" name = "nuon" -version = "0.95.0" +version = "0.95.1" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -nu-parser = { path = "../nu-parser", version = "0.95.0" } -nu-protocol = { path = "../nu-protocol", version = "0.95.0" } -nu-engine = { path = "../nu-engine", version = "0.95.0" } +nu-parser = { path = "../nu-parser", version = "0.95.1" } +nu-protocol = { path = "../nu-protocol", version = "0.95.1" } +nu-engine = { path = "../nu-engine", version = "0.95.1" } once_cell = { workspace = true } fancy-regex = { workspace = true } From f241110005006f10e16c6080ebab7abec6f3e5ce Mon Sep 17 00:00:00 2001 From: Darren Schroeder <343840+fdncred@users.noreply.github.com> Date: Tue, 25 Jun 2024 20:31:54 -0500 Subject: [PATCH 02/16] implement autoloading (#13217) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description This PR implements script or module autoloading. It does this by finding the `$nu.vendor-autoload-dir`, lists the contents and sorts them by file name. These files are evaluated in that order. To see what's going on, you can use `--log-level warn` ``` ❯ cargo r -- --log-level warn Finished dev [unoptimized + debuginfo] target(s) in 0.58s Running `target\debug\nu.exe --log-level warn` 2024-06-24 09:23:20.494 PM [WARN ] nu::config_files: set_config_path() cwd: "C:\\Users\\fdncred\\source\\repos\\nushell", default_config: config.nu, key: config-path, config_file_specified: None 2024-06-24 09:23:20.495 PM [WARN ] nu::config_files: set_config_path() cwd: "C:\\Users\\fdncred\\source\\repos\\nushell", default_config: env.nu, key: env-path, config_file_specified: None 2024-06-24 09:23:20.629 PM [WARN ] nu::config_files: setup_config() config_file_specified: None, env_file_specified: None, login: false 2024-06-24 09:23:20.660 PM [WARN ] nu::config_files: read_config_file() config_file_specified: None, is_env_config: true Hello, from env.nu 2024-06-24 09:23:20.679 PM [WARN ] nu::config_files: read_config_file() config_file_specified: None, is_env_config: false Hello, from config.nu Hello, from defs.nu Activating Microsoft Visual Studio environment. 2024-06-24 09:23:21.398 PM [WARN ] nu::config_files: read_vendor_autoload_files() src\config_files.rs:234:9 2024-06-24 09:23:21.399 PM [WARN ] nu::config_files: read_vendor_autoload_files: C:\ProgramData\nushell\vendor\autoload 2024-06-24 09:23:21.399 PM [WARN ] nu::config_files: AutoLoading: "C:\\ProgramData\\nushell\\vendor\\autoload\\01_get-weather.nu" 2024-06-24 09:23:21.675 PM [WARN ] nu::config_files: AutoLoading: "C:\\ProgramData\\nushell\\vendor\\autoload\\02_temp.nu" 2024-06-24 09:23:21.817 PM [WARN ] nu_cli::repl: Terminal doesn't support use_kitty_protocol config ``` # User-Facing Changes # Tests + Formatting # After Submitting --- crates/nu-protocol/src/eval_const.rs | 65 +++++++++++++++++----------- src/config_files.rs | 45 ++++++++++++++++++- 2 files changed, 84 insertions(+), 26 deletions(-) diff --git a/crates/nu-protocol/src/eval_const.rs b/crates/nu-protocol/src/eval_const.rs index 8f6382ae44..87913e4ee3 100644 --- a/crates/nu-protocol/src/eval_const.rs +++ b/crates/nu-protocol/src/eval_const.rs @@ -194,31 +194,11 @@ pub(crate) fn create_nu_constant(engine_state: &EngineState, span: Span) -> Valu // if not, use the default /usr/share/nushell/vendor/autoload // check to see if NU_VENDOR_AUTOLOAD_DIR env var is set, if not, use the default - Value::string( - option_env!("NU_VENDOR_AUTOLOAD_DIR") - .map(String::from) - .unwrap_or_else(|| { - if cfg!(windows) { - let all_user_profile = match engine_state.get_env_var("ALLUSERPROFILE") { - Some(v) => format!( - "{}\\nushell\\vendor\\autoload", - v.coerce_string().unwrap_or("C:\\ProgramData".into()) - ), - None => "C:\\ProgramData\\nushell\\vendor\\autoload".into(), - }; - all_user_profile - } else { - // In non-Windows environments, if NU_VENDOR_AUTOLOAD_DIR is not set - // check to see if PREFIX env var is set, and use it as PREFIX/nushell/vendor/autoload - // otherwise default to /usr/share/nushell/vendor/autoload - option_env!("PREFIX").map(String::from).map_or_else( - || "/usr/local/share/nushell/vendor/autoload".into(), - |prefix| format!("{}/share/nushell/vendor/autoload", prefix), - ) - } - }), - span, - ), + if let Some(path) = get_vendor_autoload_dir(engine_state) { + Value::string(path.to_string_lossy(), span) + } else { + Value::error(ShellError::ConfigDirNotFound { span: Some(span) }, span) + }, ); record.push("temp-path", { @@ -275,6 +255,41 @@ pub(crate) fn create_nu_constant(engine_state: &EngineState, span: Span) -> Valu Value::record(record, span) } +pub fn get_vendor_autoload_dir(engine_state: &EngineState) -> Option { + // pseudo code + // if env var NU_VENDOR_AUTOLOAD_DIR is set, in any platform, use it + // if not, if windows, use ALLUSERPROFILE\nushell\vendor\autoload + // if not, if non-windows, if env var PREFIX is set, use PREFIX/share/nushell/vendor/autoload + // if not, use the default /usr/share/nushell/vendor/autoload + + // check to see if NU_VENDOR_AUTOLOAD_DIR env var is set, if not, use the default + Some( + option_env!("NU_VENDOR_AUTOLOAD_DIR") + .map(String::from) + .unwrap_or_else(|| { + if cfg!(windows) { + let all_user_profile = match engine_state.get_env_var("ALLUSERPROFILE") { + Some(v) => format!( + "{}\\nushell\\vendor\\autoload", + v.coerce_string().unwrap_or("C:\\ProgramData".into()) + ), + None => "C:\\ProgramData\\nushell\\vendor\\autoload".into(), + }; + all_user_profile + } else { + // In non-Windows environments, if NU_VENDOR_AUTOLOAD_DIR is not set + // check to see if PREFIX env var is set, and use it as PREFIX/nushell/vendor/autoload + // otherwise default to /usr/share/nushell/vendor/autoload + option_env!("PREFIX").map(String::from).map_or_else( + || "/usr/local/share/nushell/vendor/autoload".into(), + |prefix| format!("{}/share/nushell/vendor/autoload", prefix), + ) + } + }) + .into(), + ) +} + fn eval_const_call( working_set: &StateWorkingSet, call: &Call, diff --git a/src/config_files.rs b/src/config_files.rs index ec4511860f..30977a6d0e 100644 --- a/src/config_files.rs +++ b/src/config_files.rs @@ -9,8 +9,9 @@ use nu_protocol::{ }; use nu_utils::{get_default_config, get_default_env}; use std::{ + fs, fs::File, - io::Write, + io::{Result, Write}, panic::{catch_unwind, AssertUnwindSafe}, path::Path, sync::Arc, @@ -176,6 +177,46 @@ pub(crate) fn read_default_env_file(engine_state: &mut EngineState, stack: &mut } } +fn read_and_sort_directory(path: &Path) -> Result> { + let mut entries = Vec::new(); + + for entry in fs::read_dir(path)? { + let entry = entry?; + let file_name = entry.file_name(); + let file_name_str = file_name.into_string().unwrap_or_default(); + entries.push(file_name_str); + } + + entries.sort(); + + Ok(entries) +} + +pub(crate) fn read_vendor_autoload_files(engine_state: &mut EngineState, stack: &mut Stack) { + warn!( + "read_vendor_autoload_files() {}:{}:{}", + file!(), + line!(), + column!() + ); + + // read and source vendor_autoload_files file if exists + if let Some(autoload_dir) = nu_protocol::eval_const::get_vendor_autoload_dir(engine_state) { + warn!("read_vendor_autoload_files: {}", autoload_dir.display()); + + if autoload_dir.exists() { + let entries = read_and_sort_directory(&autoload_dir); + if let Ok(entries) = entries { + for entry in entries { + let path = autoload_dir.join(entry); + warn!("AutoLoading: {:?}", path); + eval_config_contents(path, engine_state, stack); + } + } + } + } +} + fn eval_default_config( engine_state: &mut EngineState, stack: &mut Stack, @@ -236,6 +277,8 @@ pub(crate) fn setup_config( if is_login_shell { read_loginshell_file(engine_state, stack); } + // read and auto load vendor autoload files + read_vendor_autoload_files(engine_state, stack); })); if result.is_err() { eprintln!( From 55ee47630639ad6032dc7ba98bd956039595600e Mon Sep 17 00:00:00 2001 From: Ian Manske Date: Wed, 26 Jun 2024 01:32:54 +0000 Subject: [PATCH 03/16] Define keywords (#13213) # Description Some commands in `nu-cmd-lang` are not classified as keywords even though they should be. # User-Facing Changes In the output of `which`, `scope commands`, and `help commands`, some commands will now have a `type` of `keyword` instead of `built-in`. --- .../nu-cmd-lang/src/core_commands/break_.rs | 10 +++++ .../src/core_commands/continue_.rs | 9 ++++ crates/nu-cmd-lang/src/core_commands/if_.rs | 11 ++++- crates/nu-cmd-lang/src/core_commands/loop_.rs | 10 +++++ .../nu-cmd-lang/src/core_commands/match_.rs | 11 ++++- .../src/core_commands/scope/command.rs | 5 --- crates/nu-cmd-lang/src/core_commands/try_.rs | 11 ++++- .../nu-cmd-lang/src/core_commands/while_.rs | 10 +++++ crates/nu-command/src/env/export_env.rs | 10 +++++ crates/nu-command/src/env/source_env.rs | 10 +++++ crates/nu-command/src/filters/where_.rs | 6 ++- crates/nu-parser/src/parse_keywords.rs | 42 ++++++++++++------- crates/nu-parser/src/parser.rs | 13 +++--- 13 files changed, 126 insertions(+), 32 deletions(-) diff --git a/crates/nu-cmd-lang/src/core_commands/break_.rs b/crates/nu-cmd-lang/src/core_commands/break_.rs index 4698f12c34..90cc1a73f2 100644 --- a/crates/nu-cmd-lang/src/core_commands/break_.rs +++ b/crates/nu-cmd-lang/src/core_commands/break_.rs @@ -1,4 +1,5 @@ use nu_engine::command_prelude::*; +use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Break; @@ -18,6 +19,15 @@ impl Command for Break { .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 command_type(&self) -> CommandType { + CommandType::Keyword + } + fn run( &self, _engine_state: &EngineState, diff --git a/crates/nu-cmd-lang/src/core_commands/continue_.rs b/crates/nu-cmd-lang/src/core_commands/continue_.rs index f65a983269..cfa3e38335 100644 --- a/crates/nu-cmd-lang/src/core_commands/continue_.rs +++ b/crates/nu-cmd-lang/src/core_commands/continue_.rs @@ -1,4 +1,5 @@ use nu_engine::command_prelude::*; +use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Continue; @@ -18,6 +19,14 @@ impl Command for Continue { .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 command_type(&self) -> CommandType { + CommandType::Keyword + } fn run( &self, _engine_state: &EngineState, diff --git a/crates/nu-cmd-lang/src/core_commands/if_.rs b/crates/nu-cmd-lang/src/core_commands/if_.rs index a2071530ac..738d901759 100644 --- a/crates/nu-cmd-lang/src/core_commands/if_.rs +++ b/crates/nu-cmd-lang/src/core_commands/if_.rs @@ -2,7 +2,7 @@ use nu_engine::{ command_prelude::*, get_eval_block, get_eval_expression, get_eval_expression_with_input, }; use nu_protocol::{ - engine::StateWorkingSet, + engine::{CommandType, StateWorkingSet}, eval_const::{eval_const_subexpression, eval_constant, eval_constant_with_input}, }; @@ -41,6 +41,15 @@ impl Command for If { .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 command_type(&self) -> CommandType { + CommandType::Keyword + } + fn is_const(&self) -> bool { true } diff --git a/crates/nu-cmd-lang/src/core_commands/loop_.rs b/crates/nu-cmd-lang/src/core_commands/loop_.rs index 9b1e36a057..a9c642ca3c 100644 --- a/crates/nu-cmd-lang/src/core_commands/loop_.rs +++ b/crates/nu-cmd-lang/src/core_commands/loop_.rs @@ -1,4 +1,5 @@ use nu_engine::{command_prelude::*, get_eval_block}; +use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Loop; @@ -20,6 +21,15 @@ impl Command for Loop { .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 command_type(&self) -> CommandType { + CommandType::Keyword + } + fn run( &self, engine_state: &EngineState, diff --git a/crates/nu-cmd-lang/src/core_commands/match_.rs b/crates/nu-cmd-lang/src/core_commands/match_.rs index 41b5c24702..d28a59cbad 100644 --- a/crates/nu-cmd-lang/src/core_commands/match_.rs +++ b/crates/nu-cmd-lang/src/core_commands/match_.rs @@ -1,7 +1,7 @@ use nu_engine::{ command_prelude::*, get_eval_block, get_eval_expression, get_eval_expression_with_input, }; -use nu_protocol::engine::Matcher; +use nu_protocol::engine::{CommandType, Matcher}; #[derive(Clone)] pub struct Match; @@ -27,6 +27,15 @@ impl Command for Match { .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 command_type(&self) -> CommandType { + CommandType::Keyword + } + fn run( &self, engine_state: &EngineState, diff --git a/crates/nu-cmd-lang/src/core_commands/scope/command.rs b/crates/nu-cmd-lang/src/core_commands/scope/command.rs index 98439226cf..cc52a8a16f 100644 --- a/crates/nu-cmd-lang/src/core_commands/scope/command.rs +++ b/crates/nu-cmd-lang/src/core_commands/scope/command.rs @@ -1,5 +1,4 @@ use nu_engine::{command_prelude::*, get_full_help}; -use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Scope; @@ -20,10 +19,6 @@ impl Command for Scope { "Commands for getting info about what is in scope." } - fn command_type(&self) -> CommandType { - CommandType::Keyword - } - fn run( &self, engine_state: &EngineState, diff --git a/crates/nu-cmd-lang/src/core_commands/try_.rs b/crates/nu-cmd-lang/src/core_commands/try_.rs index 1f16f97908..f99825b88d 100644 --- a/crates/nu-cmd-lang/src/core_commands/try_.rs +++ b/crates/nu-cmd-lang/src/core_commands/try_.rs @@ -1,5 +1,5 @@ use nu_engine::{command_prelude::*, get_eval_block, EvalBlockFn}; -use nu_protocol::engine::Closure; +use nu_protocol::engine::{Closure, CommandType}; #[derive(Clone)] pub struct Try; @@ -31,6 +31,15 @@ impl Command for Try { .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 command_type(&self) -> CommandType { + CommandType::Keyword + } + fn run( &self, engine_state: &EngineState, diff --git a/crates/nu-cmd-lang/src/core_commands/while_.rs b/crates/nu-cmd-lang/src/core_commands/while_.rs index bf9076aa0c..646b95c82e 100644 --- a/crates/nu-cmd-lang/src/core_commands/while_.rs +++ b/crates/nu-cmd-lang/src/core_commands/while_.rs @@ -1,4 +1,5 @@ use nu_engine::{command_prelude::*, get_eval_block, get_eval_expression}; +use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct While; @@ -29,6 +30,15 @@ impl Command for While { vec!["loop"] } + 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 command_type(&self) -> CommandType { + CommandType::Keyword + } + fn run( &self, engine_state: &EngineState, diff --git a/crates/nu-command/src/env/export_env.rs b/crates/nu-command/src/env/export_env.rs index 20605a9bb5..00f2c73ef4 100644 --- a/crates/nu-command/src/env/export_env.rs +++ b/crates/nu-command/src/env/export_env.rs @@ -1,4 +1,5 @@ use nu_engine::{command_prelude::*, get_eval_block, redirect_env}; +use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct ExportEnv; @@ -23,6 +24,15 @@ impl Command for ExportEnv { "Run a block and preserve its environment in a current scope." } + 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 command_type(&self) -> CommandType { + CommandType::Keyword + } + fn run( &self, engine_state: &EngineState, diff --git a/crates/nu-command/src/env/source_env.rs b/crates/nu-command/src/env/source_env.rs index 71c1e6dc3f..0d8b118e8d 100644 --- a/crates/nu-command/src/env/source_env.rs +++ b/crates/nu-command/src/env/source_env.rs @@ -2,6 +2,7 @@ use nu_engine::{ command_prelude::*, find_in_dirs_env, get_dirs_var_from_call, get_eval_block_with_early_return, redirect_env, }; +use nu_protocol::engine::CommandType; use std::path::PathBuf; /// Source a file for environment variables. @@ -28,6 +29,15 @@ impl Command for SourceEnv { "Source the environment from a source file into the current environment." } + 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 command_type(&self) -> CommandType { + CommandType::Keyword + } + fn run( &self, engine_state: &EngineState, diff --git a/crates/nu-command/src/filters/where_.rs b/crates/nu-command/src/filters/where_.rs index fe73de354f..922879d09b 100644 --- a/crates/nu-command/src/filters/where_.rs +++ b/crates/nu-command/src/filters/where_.rs @@ -1,5 +1,5 @@ use nu_engine::{command_prelude::*, ClosureEval}; -use nu_protocol::engine::Closure; +use nu_protocol::engine::{Closure, CommandType}; #[derive(Clone)] pub struct Where; @@ -19,6 +19,10 @@ tables, known as "row conditions". On the other hand, reading the condition from not supported."# } + fn command_type(&self) -> CommandType { + CommandType::Keyword + } + fn signature(&self) -> nu_protocol::Signature { Signature::build("where") .input_output_types(vec![ diff --git a/crates/nu-parser/src/parse_keywords.rs b/crates/nu-parser/src/parse_keywords.rs index 673a59fb05..6d3862db37 100644 --- a/crates/nu-parser/src/parse_keywords.rs +++ b/crates/nu-parser/src/parse_keywords.rs @@ -42,32 +42,44 @@ use crate::{ }; /// These parser keywords can be aliased -pub const ALIASABLE_PARSER_KEYWORDS: &[&[u8]] = &[b"overlay hide", b"overlay new", b"overlay use"]; +pub const ALIASABLE_PARSER_KEYWORDS: &[&[u8]] = &[ + b"if", + b"match", + b"try", + b"overlay", + b"overlay hide", + b"overlay new", + b"overlay use", +]; pub const RESERVED_VARIABLE_NAMES: [&str; 3] = ["in", "nu", "env"]; /// These parser keywords cannot be aliased (either not possible, or support not yet added) pub const UNALIASABLE_PARSER_KEYWORDS: &[&[u8]] = &[ - b"export", - b"def", - b"export def", - b"for", - b"extern", - b"export extern", b"alias", - b"export alias", - b"export-env", + b"const", + b"def", + b"extern", b"module", b"use", + b"export", + b"export alias", + b"export const", + b"export def", + b"export extern", + b"export module", b"export use", - b"hide", - // b"overlay", - // b"overlay hide", - // b"overlay new", - // b"overlay use", + b"for", + b"loop", + b"while", + b"return", + b"break", + b"continue", b"let", - b"const", b"mut", + b"hide", + b"export-env", + b"source-env", b"source", b"where", b"register", diff --git a/crates/nu-parser/src/parser.rs b/crates/nu-parser/src/parser.rs index ba718cc771..1fef8bc133 100644 --- a/crates/nu-parser/src/parser.rs +++ b/crates/nu-parser/src/parser.rs @@ -934,15 +934,12 @@ pub fn parse_internal_call( let output = signature.get_output_type(); // storing the var ID for later due to borrowing issues - let lib_dirs_var_id = if decl.is_builtin() { - match decl.name() { - "use" | "overlay use" | "source-env" | "nu-check" => { - find_dirs_var(working_set, LIB_DIRS_VAR) - } - _ => None, + let lib_dirs_var_id = match decl.name() { + "use" | "overlay use" | "source-env" if decl.is_keyword() => { + find_dirs_var(working_set, LIB_DIRS_VAR) } - } else { - None + "nu-check" if decl.is_builtin() => find_dirs_var(working_set, LIB_DIRS_VAR), + _ => None, }; // The index into the positional parameter in the definition From def36865effde927b919c3221f1ee44b05798770 Mon Sep 17 00:00:00 2001 From: Wind Date: Wed, 26 Jun 2024 09:33:37 +0800 Subject: [PATCH 04/16] Enable reloading changes to a submodule (#13170) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Fixes: https://github.com/nushell/nushell/issues/12099 Currently if user run `use voice.nu`, and file is unchanged, then run `use voice.nu` again. nushell will use the module directly, even if submodule inside `voice.nu` is changed. After discussed with @kubouch, I think it's ok to re-parse the module file when: 1. It exports sub modules which are defined by a file 2. It uses other modules which are defined by a file ## About the change: To achieve the behavior, we need to add 2 attributes to `Module`: 1. `imported_modules`: it tracks the other modules is imported by the givem `module`, e.g: `use foo.nu` 2. `file`: the path of a module, if a module is defined by a file, it will be `Some(path)`, or else it will be `None`. After the change: use voice.nu always read the file and parse it. use voice will still use the module which is saved in EngineState. # User-Facing Changes use `xxx.nu` will read the file and parse it if it exports submodules or uses submodules # Tests + Formatting Done --------- Co-authored-by: Jakub Žádník --- crates/nu-parser/src/lib.rs | 3 +- crates/nu-parser/src/parse_keywords.rs | 71 +++++++- crates/nu-parser/src/parser.rs | 2 +- crates/nu-protocol/src/lib.rs | 1 + crates/nu-protocol/src/module.rs | 35 +++- .../src/parser_path.rs | 2 +- tests/modules/mod.rs | 161 +++++++++++++++++- 7 files changed, 258 insertions(+), 17 deletions(-) rename crates/{nu-parser => nu-protocol}/src/parser_path.rs (98%) diff --git a/crates/nu-parser/src/lib.rs b/crates/nu-parser/src/lib.rs index eeb6a590b8..89cba8d243 100644 --- a/crates/nu-parser/src/lib.rs +++ b/crates/nu-parser/src/lib.rs @@ -8,7 +8,6 @@ mod parse_keywords; mod parse_patterns; mod parse_shape_specs; mod parser; -mod parser_path; mod type_check; pub use deparse::{escape_for_script_arg, escape_quote_string}; @@ -18,8 +17,8 @@ pub use flatten::{ pub use known_external::KnownExternal; pub use lex::{lex, lex_signature, Token, TokenContents}; pub use lite_parser::{lite_parse, LiteBlock, LiteCommand}; +pub use nu_protocol::parser_path::*; pub use parse_keywords::*; -pub use parser_path::*; pub use parser::{ is_math_expression_like, parse, parse_block, parse_expression, parse_external_call, diff --git a/crates/nu-parser/src/parse_keywords.rs b/crates/nu-parser/src/parse_keywords.rs index 6d3862db37..70d217c564 100644 --- a/crates/nu-parser/src/parse_keywords.rs +++ b/crates/nu-parser/src/parse_keywords.rs @@ -2,7 +2,6 @@ use crate::{ exportable::Exportable, parse_block, parser::{parse_redirection, redirecting_builtin_error}, - parser_path::ParserPath, type_check::{check_block_input_output, type_compatible}, }; use itertools::Itertools; @@ -15,6 +14,7 @@ use nu_protocol::{ }, engine::{StateWorkingSet, DEFAULT_OVERLAY_NAME}, eval_const::eval_constant, + parser_path::ParserPath, Alias, BlockId, DeclId, Module, ModuleId, ParseError, PositionalArg, ResolvedImportPattern, Span, Spanned, SyntaxShape, Type, Value, VarId, }; @@ -1204,7 +1204,7 @@ pub fn parse_export_in_block( "export alias" => parse_alias(working_set, lite_command, None), "export def" => parse_def(working_set, lite_command, None).0, "export const" => parse_const(working_set, &lite_command.parts[1..]), - "export use" => parse_use(working_set, lite_command).0, + "export use" => parse_use(working_set, lite_command, None).0, "export module" => parse_module(working_set, lite_command, None).0, "export extern" => parse_extern(working_set, lite_command, None), _ => { @@ -1223,6 +1223,7 @@ pub fn parse_export_in_module( working_set: &mut StateWorkingSet, lite_command: &LiteCommand, module_name: &[u8], + parent_module: &mut Module, ) -> (Pipeline, Vec) { let spans = &lite_command.parts[..]; @@ -1428,7 +1429,8 @@ pub fn parse_export_in_module( pipe: lite_command.pipe, redirection: lite_command.redirection.clone(), }; - let (pipeline, exportables) = parse_use(working_set, &lite_command); + let (pipeline, exportables) = + parse_use(working_set, &lite_command, Some(parent_module)); let export_use_decl_id = if let Some(id) = working_set.find_decl(b"export use") { id @@ -1771,7 +1773,7 @@ pub fn parse_module_block( )) } b"use" => { - let (pipeline, _) = parse_use(working_set, command); + let (pipeline, _) = parse_use(working_set, command, Some(&mut module)); block.pipelines.push(pipeline) } @@ -1786,7 +1788,7 @@ pub fn parse_module_block( } b"export" => { let (pipe, exportables) = - parse_export_in_module(working_set, command, module_name); + parse_export_in_module(working_set, command, module_name, &mut module); for exportable in exportables { match exportable { @@ -1896,6 +1898,48 @@ pub fn parse_module_block( (block, module, module_comments) } +fn module_needs_reloading(working_set: &StateWorkingSet, module_id: ModuleId) -> bool { + let module = working_set.get_module(module_id); + + fn submodule_need_reloading(working_set: &StateWorkingSet, submodule_id: ModuleId) -> bool { + let submodule = working_set.get_module(submodule_id); + let submodule_changed = if let Some((file_path, file_id)) = &submodule.file { + let existing_contents = working_set.get_contents_of_file(*file_id); + let file_contents = file_path.read(working_set); + + if let (Some(existing), Some(new)) = (existing_contents, file_contents) { + existing != new + } else { + false + } + } else { + false + }; + + if submodule_changed { + true + } else { + module_needs_reloading(working_set, submodule_id) + } + } + + let export_submodule_changed = module + .submodules + .iter() + .any(|(_, submodule_id)| submodule_need_reloading(working_set, *submodule_id)); + + if export_submodule_changed { + return true; + } + + let private_submodule_changed = module + .imported_modules + .iter() + .any(|submodule_id| submodule_need_reloading(working_set, *submodule_id)); + + private_submodule_changed +} + /// Parse a module from a file. /// /// The module name is inferred from the stem of the file, unless specified in `name_override`. @@ -1934,23 +1978,26 @@ fn parse_module_file( // Check if we've parsed the module before. if let Some(module_id) = working_set.find_module_by_span(new_span) { - return Some(module_id); + if !module_needs_reloading(working_set, module_id) { + return Some(module_id); + } } // Add the file to the stack of files being processed. - if let Err(e) = working_set.files.push(path.path_buf(), path_span) { + if let Err(e) = working_set.files.push(path.clone().path_buf(), path_span) { working_set.error(e); return None; } // Parse the module - let (block, module, module_comments) = + let (block, mut module, module_comments) = parse_module_block(working_set, new_span, module_name.as_bytes()); // Remove the file from the stack of files being processed. working_set.files.pop(); let _ = working_set.add_block(Arc::new(block)); + module.file = Some((path, file_id)); let module_id = working_set.add_module(&module_name, module, module_comments); Some(module_id) @@ -2240,6 +2287,7 @@ pub fn parse_module( pub fn parse_use( working_set: &mut StateWorkingSet, lite_command: &LiteCommand, + parent_module: Option<&mut Module>, ) -> (Pipeline, Vec) { let spans = &lite_command.parts; @@ -2385,12 +2433,14 @@ pub fn parse_use( ); }; + let mut imported_modules = vec![]; let (definitions, errors) = module.resolve_import_pattern( working_set, module_id, &import_pattern.members, None, name_span, + &mut imported_modules, ); working_set.parse_errors.extend(errors); @@ -2432,6 +2482,9 @@ pub fn parse_use( import_pattern.constants = constants.iter().map(|(_, id)| *id).collect(); + if let Some(m) = parent_module { + m.track_imported_modules(&imported_modules) + } // Extend the current scope with the module's exportables working_set.use_decls(definitions.decls); working_set.use_modules(definitions.modules); @@ -2865,6 +2918,7 @@ pub fn parse_overlay_use(working_set: &mut StateWorkingSet, call: Box) -> &[], Some(final_overlay_name.as_bytes()), call.head, + &mut vec![], ) } else { origin_module.resolve_import_pattern( @@ -2875,6 +2929,7 @@ pub fn parse_overlay_use(working_set: &mut StateWorkingSet, call: Box) -> }], Some(final_overlay_name.as_bytes()), call.head, + &mut vec![], ) } } else { diff --git a/crates/nu-parser/src/parser.rs b/crates/nu-parser/src/parser.rs index 1fef8bc133..f6bbd84f6c 100644 --- a/crates/nu-parser/src/parser.rs +++ b/crates/nu-parser/src/parser.rs @@ -5377,7 +5377,7 @@ pub fn parse_builtin_commands( } b"alias" => parse_alias(working_set, lite_command, None), b"module" => parse_module(working_set, lite_command, None).0, - b"use" => parse_use(working_set, lite_command).0, + b"use" => parse_use(working_set, lite_command, None).0, b"overlay" => { if let Some(redirection) = lite_command.redirection.as_ref() { working_set.error(redirecting_builtin_error("overlay", redirection)); diff --git a/crates/nu-protocol/src/lib.rs b/crates/nu-protocol/src/lib.rs index 78e7d40680..9c176953d5 100644 --- a/crates/nu-protocol/src/lib.rs +++ b/crates/nu-protocol/src/lib.rs @@ -11,6 +11,7 @@ mod example; mod id; mod lev_distance; mod module; +pub mod parser_path; mod pipeline; #[cfg(feature = "plugin")] mod plugin; diff --git a/crates/nu-protocol/src/module.rs b/crates/nu-protocol/src/module.rs index ebb6f5621e..6b4aec0c60 100644 --- a/crates/nu-protocol/src/module.rs +++ b/crates/nu-protocol/src/module.rs @@ -1,8 +1,9 @@ use crate::{ - ast::ImportPatternMember, engine::StateWorkingSet, BlockId, DeclId, ModuleId, ParseError, Span, - Value, VarId, + ast::ImportPatternMember, engine::StateWorkingSet, BlockId, DeclId, FileId, ModuleId, + ParseError, Span, Value, VarId, }; +use crate::parser_path::ParserPath; use indexmap::IndexMap; pub struct ResolvedImportPattern { @@ -35,6 +36,8 @@ pub struct Module { pub env_block: Option, // `export-env { ... }` block pub main: Option, // `export def main` pub span: Option, + pub imported_modules: Vec, // use other_module.nu + pub file: Option<(ParserPath, FileId)>, } impl Module { @@ -47,6 +50,8 @@ impl Module { env_block: None, main: None, span: None, + imported_modules: vec![], + file: None, } } @@ -59,6 +64,8 @@ impl Module { env_block: None, main: None, span: Some(span), + imported_modules: vec![], + file: None, } } @@ -82,6 +89,12 @@ impl Module { self.env_block = Some(block_id); } + pub fn track_imported_modules(&mut self, module_id: &[ModuleId]) { + for m in module_id { + self.imported_modules.push(*m) + } + } + pub fn has_decl(&self, name: &[u8]) -> bool { if name == self.name && self.main.is_some() { return true; @@ -90,6 +103,9 @@ impl Module { self.decls.contains_key(name) } + /// Resolve `members` from given module, which is indicated by `self_id` to import. + /// + /// When resolving, all modules are recorded in `imported_modules`. pub fn resolve_import_pattern( &self, working_set: &StateWorkingSet, @@ -97,7 +113,9 @@ impl Module { members: &[ImportPatternMember], name_override: Option<&[u8]>, // name under the module was stored (doesn't have to be the same as self.name) backup_span: Span, + imported_modules: &mut Vec, ) -> (ResolvedImportPattern, Vec) { + imported_modules.push(self_id); let final_name = name_override.unwrap_or(&self.name).to_vec(); let (head, rest) = if let Some((head, rest)) = members.split_first() { @@ -112,8 +130,14 @@ impl Module { let submodule = working_set.get_module(*id); let span = submodule.span.or(self.span).unwrap_or(backup_span); - let (sub_results, sub_errors) = - submodule.resolve_import_pattern(working_set, *id, &[], None, span); + let (sub_results, sub_errors) = submodule.resolve_import_pattern( + working_set, + *id, + &[], + None, + span, + imported_modules, + ); errors.extend(sub_errors); for (sub_name, sub_decl_id) in sub_results.decls { @@ -212,6 +236,7 @@ impl Module { rest, None, self.span.unwrap_or(backup_span), + imported_modules, ) } else { ( @@ -234,6 +259,7 @@ impl Module { &[], None, self.span.unwrap_or(backup_span), + imported_modules, ); decls.extend(sub_results.decls); @@ -287,6 +313,7 @@ impl Module { rest, None, self.span.unwrap_or(backup_span), + imported_modules, ); decls.extend(sub_results.decls); diff --git a/crates/nu-parser/src/parser_path.rs b/crates/nu-protocol/src/parser_path.rs similarity index 98% rename from crates/nu-parser/src/parser_path.rs rename to crates/nu-protocol/src/parser_path.rs index 2d0fbce2a2..4935d9fbe2 100644 --- a/crates/nu-parser/src/parser_path.rs +++ b/crates/nu-protocol/src/parser_path.rs @@ -1,4 +1,4 @@ -use nu_protocol::engine::{StateWorkingSet, VirtualPath}; +use crate::engine::{StateWorkingSet, VirtualPath}; use std::{ ffi::OsStr, path::{Path, PathBuf}, diff --git a/tests/modules/mod.rs b/tests/modules/mod.rs index c556d6fa7a..9aa1282f21 100644 --- a/tests/modules/mod.rs +++ b/tests/modules/mod.rs @@ -1,4 +1,4 @@ -use nu_test_support::fs::Stub::FileWithContentToBeTrimmed; +use nu_test_support::fs::Stub::{FileWithContent, FileWithContentToBeTrimmed}; use nu_test_support::playground::Playground; use nu_test_support::{nu, nu_repl_code}; use pretty_assertions::assert_eq; @@ -760,3 +760,162 @@ fn nested_list_export_works() { let actual = nu!(&inp.join("; ")); assert_eq!(actual.out, "bacon"); } + +#[test] +fn reload_submodules() { + Playground::setup("reload_submodule_changed_file", |dirs, sandbox| { + sandbox.with_files(&[ + FileWithContent("voice.nu", r#"export module animals.nu"#), + FileWithContent("animals.nu", "export def cat [] { 'meow'}"), + ]); + + let inp = [ + "use voice.nu", + r#""export def cat [] {'woem'}" | save -f animals.nu"#, + "use voice.nu", + "(voice animals cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + + // should also verify something unchanged if `use voice`. + let inp = [ + "use voice.nu", + r#""export def cat [] {'meow'}" | save -f animals.nu"#, + "use voice", + "(voice animals cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + + // should also works if we use members directly. + sandbox.with_files(&[ + FileWithContent("voice.nu", r#"export module animals.nu"#), + FileWithContent("animals.nu", "export def cat [] { 'meow'}"), + ]); + let inp = [ + "use voice.nu animals cat", + r#""export def cat [] {'woem'}" | save -f animals.nu"#, + "use voice.nu animals cat", + "(cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + }); +} + +#[test] +fn use_submodules() { + Playground::setup("use_submodules", |dirs, sandbox| { + sandbox.with_files(&[ + FileWithContent("voice.nu", r#"export use animals.nu"#), + FileWithContent("animals.nu", "export def cat [] { 'meow'}"), + ]); + + let inp = [ + "use voice.nu", + r#""export def cat [] {'woem'}" | save -f animals.nu"#, + "use voice.nu", + "(voice animals cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + + // should also verify something unchanged if `use voice`. + let inp = [ + "use voice.nu", + r#""export def cat [] {'meow'}" | save -f animals.nu"#, + "use voice", + "(voice animals cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + + // also verify something is changed when using members. + sandbox.with_files(&[ + FileWithContent("voice.nu", r#"export use animals.nu cat"#), + FileWithContent("animals.nu", "export def cat [] { 'meow'}"), + ]); + let inp = [ + "use voice.nu", + r#""export def cat [] {'woem'}" | save -f animals.nu"#, + "use voice.nu", + "(voice cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + + sandbox.with_files(&[ + FileWithContent("voice.nu", r#"export use animals.nu *"#), + FileWithContent("animals.nu", "export def cat [] { 'meow'}"), + ]); + let inp = [ + "use voice.nu", + r#""export def cat [] {'woem'}" | save -f animals.nu"#, + "use voice.nu", + "(voice cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + + sandbox.with_files(&[ + FileWithContent("voice.nu", r#"export use animals.nu [cat]"#), + FileWithContent("animals.nu", "export def cat [] { 'meow'}"), + ]); + let inp = [ + "use voice.nu", + r#""export def cat [] {'woem'}" | save -f animals.nu"#, + "use voice.nu", + "(voice cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + }); +} + +#[test] +fn use_nested_submodules() { + Playground::setup("use_submodules", |dirs, sandbox| { + sandbox.with_files(&[ + FileWithContent("voice.nu", r#"export use animals.nu"#), + FileWithContent("animals.nu", r#"export use nested_animals.nu"#), + FileWithContent("nested_animals.nu", "export def cat [] { 'meow'}"), + ]); + let inp = [ + "use voice.nu", + r#""export def cat [] {'woem'}" | save -f nested_animals.nu"#, + "use voice.nu", + "(voice animals nested_animals cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + + sandbox.with_files(&[ + FileWithContent("voice.nu", r#"export use animals.nu"#), + FileWithContent("animals.nu", r#"export use nested_animals.nu cat"#), + FileWithContent("nested_animals.nu", "export def cat [] { 'meow'}"), + ]); + let inp = [ + "use voice.nu", + r#""export def cat [] {'woem'}" | save -f nested_animals.nu"#, + "use voice.nu", + "(voice animals cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + + sandbox.with_files(&[ + FileWithContent("animals.nu", r#"export use nested_animals.nu cat"#), + FileWithContent("nested_animals.nu", "export def cat [] { 'meow' }"), + ]); + let inp = [ + "module voice { export module animals.nu }", + "use voice", + r#""export def cat [] {'woem'}" | save -f nested_animals.nu"#, + "use voice.nu", + "(voice animals cat) == 'woem'", + ]; + let actual = nu!(cwd: dirs.test(), nu_repl_code(&inp)); + assert_eq!(actual.out, "true"); + }) +} From 5a486029dbe2d33a690d325a6cc59639f07eb74f Mon Sep 17 00:00:00 2001 From: Ian Manske Date: Wed, 26 Jun 2024 01:33:57 +0000 Subject: [PATCH 05/16] Add typed path forms (#13115) # Description This PR adds new types to `nu-path` to enforce path invariants. Namely, this PR adds: - `Path` and `PathBuf`. These types are different from, but analogous to `std::path::Path` and `std::path::PathBuf`. - `RelativePath` and `RelativePathBuf`. These types must be/contain strictly relative paths. - `AbsolutePath` and `AbsolutePathBuf`. These types must be/contain strictly absolute paths. - `CanonicalPath` and `CanonicalPathBuf`. These types must be/contain canonical paths. Operations are prohibited as necessary to ensure that the invariants of each type are upheld (needs double-checking). Only paths that are absolute (or canonical) can be easily used as / converted to `std::path::Path`s. This is to help force us to account for the emulated current working directory instead of accidentally using the current directory of the Nushell process (i.e., `std::env::current_dir`). Related to #12975 and #12976. Note that this PR uses several declarative macros, as the file / this PR would otherwise be 5000 lines long. # User-Facing Changes No major changes yet, just adds types to `nu-path` to be used in the future. # After Submitting Actually use the new path types in all our crates where it makes sense, removing usages of `std::path` types. --- crates/nu-path/src/form.rs | 161 ++ crates/nu-path/src/lib.rs | 3 + crates/nu-path/src/path.rs | 3095 ++++++++++++++++++++++++++++++++++++ typos.toml | 1 + 4 files changed, 3260 insertions(+) create mode 100644 crates/nu-path/src/form.rs create mode 100644 crates/nu-path/src/path.rs diff --git a/crates/nu-path/src/form.rs b/crates/nu-path/src/form.rs new file mode 100644 index 0000000000..4266905a20 --- /dev/null +++ b/crates/nu-path/src/form.rs @@ -0,0 +1,161 @@ +use std::ffi::OsStr; + +mod private { + use std::ffi::OsStr; + + // This trait should not be extended by external crates in order to uphold safety guarantees. + // As such, this trait is put inside a private module to prevent external impls. + // This ensures that all possible [`PathForm`]s can only be defined here and will: + // - be zero sized (enforced anyways by the `repr(transparent)` on `Path`) + // - have a no-op [`Drop`] implementation + pub trait Sealed: 'static { + fn invariants_satisfied + ?Sized>(path: &P) -> bool; + } +} + +/// A marker trait for the different kinds of path forms. +/// Each form has its own invariants that are guaranteed be upheld. +/// The list of path forms are: +/// - [`Any`]: a path with no invariants. It may be a relative or an absolute path. +/// - [`Relative`]: a strictly relative path. +/// - [`Absolute`]: a strictly absolute path. +/// - [`Canonical`]: a path that must be in canonicalized form. +pub trait PathForm: private::Sealed {} +impl PathForm for Any {} +impl PathForm for Relative {} +impl PathForm for Absolute {} +impl PathForm for Canonical {} + +/// A path whose form is unknown. It could be a relative, absolute, or canonical path. +/// +/// The path is not guaranteed to be normalized. It may contain unresolved symlinks, +/// trailing slashes, dot components (`..` or `.`), and repeated path separators. +pub struct Any; + +impl private::Sealed for Any { + fn invariants_satisfied + ?Sized>(_: &P) -> bool { + true + } +} + +/// A strictly relative path. +/// +/// The path is not guaranteed to be normalized. It may contain unresolved symlinks, +/// trailing slashes, dot components (`..` or `.`), and repeated path separators. +pub struct Relative; + +impl private::Sealed for Relative { + fn invariants_satisfied + ?Sized>(path: &P) -> bool { + std::path::Path::new(path).is_relative() + } +} + +/// An absolute path. +/// +/// The path is not guaranteed to be normalized. It may contain unresolved symlinks, +/// trailing slashes, dot components (`..` or `.`), and repeated path separators. +pub struct Absolute; + +impl private::Sealed for Absolute { + fn invariants_satisfied + ?Sized>(path: &P) -> bool { + std::path::Path::new(path).is_absolute() + } +} + +// A canonical path. +// +// An absolute path with all intermediate components normalized and symbolic links resolved. +pub struct Canonical; + +impl private::Sealed for Canonical { + fn invariants_satisfied + ?Sized>(_: &P) -> bool { + true + } +} + +/// A marker trait for [`PathForm`]s that may be relative paths. +/// This includes only the [`Any`] and [`Relative`] path forms. +/// +/// [`push`](crate::PathBuf::push) and [`join`](crate::Path::join) +/// operations only support [`MaybeRelative`] path forms as input. +pub trait MaybeRelative: PathForm {} +impl MaybeRelative for Any {} +impl MaybeRelative for Relative {} + +/// A marker trait for [`PathForm`]s that may be absolute paths. +/// This includes the [`Any`], [`Absolute`], and [`Canonical`] path forms. +pub trait MaybeAbsolute: PathForm {} +impl MaybeAbsolute for Any {} +impl MaybeAbsolute for Absolute {} +impl MaybeAbsolute for Canonical {} + +/// A marker trait for [`PathForm`]s that are absolute paths. +/// This includes only the [`Absolute`] and [`Canonical`] path forms. +/// +/// Only [`PathForm`]s that implement this trait can be easily converted to [`std::path::Path`] +/// or [`std::path::PathBuf`]. This is to encourage/force other Nushell crates to account for +/// the emulated current working directory, instead of using the [`std::env::current_dir`]. +pub trait IsAbsolute: PathForm {} +impl IsAbsolute for Absolute {} +impl IsAbsolute for Canonical {} + +/// A marker trait that signifies one [`PathForm`] can be used as or trivially converted to +/// another [`PathForm`]. +/// +/// The list of possible conversions are: +/// - [`Relative`], [`Absolute`], or [`Canonical`] into [`Any`]. +/// - [`Canonical`] into [`Absolute`]. +/// - Any form into itself. +pub trait PathCast: PathForm {} +impl PathCast
for Form {} +impl PathCast for Relative {} +impl PathCast for Absolute {} +impl PathCast for Canonical {} +impl PathCast for Canonical {} + +/// A trait used to specify the output [`PathForm`] of a path join operation. +/// +/// The output path forms based on the left hand side path form are as follows: +/// +/// | Left hand side | Output form | +/// | --------------:|:------------ | +/// | [`Any`] | [`Any`] | +/// | [`Relative`] | [`Any`] | +/// | [`Absolute`] | [`Absolute`] | +/// | [`Canonical`] | [`Absolute`] | +pub trait PathJoin: PathForm { + type Output: PathForm; +} +impl PathJoin for Any { + type Output = Self; +} +impl PathJoin for Relative { + type Output = Any; +} +impl PathJoin for Absolute { + type Output = Self; +} +impl PathJoin for Canonical { + type Output = Absolute; +} + +/// A marker trait for [`PathForm`]s that support setting the file name or extension. +/// +/// This includes the [`Any`], [`Relative`], and [`Absolute`] path forms. +/// [`Canonical`] paths do not support this, since appending file names and extensions that contain +/// path separators can cause the path to no longer be canonical. +pub trait PathSet: PathForm {} +impl PathSet for Any {} +impl PathSet for Relative {} +impl PathSet for Absolute {} + +/// A marker trait for [`PathForm`]s that support pushing [`MaybeRelative`] paths. +/// +/// This includes only [`Any`] and [`Absolute`] path forms. +/// Pushing onto a [`Relative`] path could cause it to become [`Absolute`], +/// which is why they do not support pushing. +/// In the future, a `push_rel` and/or a `try_push` method could be added as an alternative. +/// Similarly, [`Canonical`] paths may become uncanonical if a non-canonical path is pushed onto it. +pub trait PathPush: PathSet {} +impl PathPush for Any {} +impl PathPush for Absolute {} diff --git a/crates/nu-path/src/lib.rs b/crates/nu-path/src/lib.rs index 13640acd2f..8553495439 100644 --- a/crates/nu-path/src/lib.rs +++ b/crates/nu-path/src/lib.rs @@ -2,12 +2,15 @@ mod assert_path_eq; mod components; pub mod dots; pub mod expansions; +pub mod form; mod helpers; +mod path; mod tilde; mod trailing_slash; pub use components::components; pub use expansions::{canonicalize_with, expand_path_with, expand_to_real_path, locate_in_dirs}; pub use helpers::{cache_dir, config_dir, data_dir, get_canonicalized_path, home_dir}; +pub use path::*; pub use tilde::expand_tilde; pub use trailing_slash::{has_trailing_slash, strip_trailing_slash}; diff --git a/crates/nu-path/src/path.rs b/crates/nu-path/src/path.rs new file mode 100644 index 0000000000..916fffdf72 --- /dev/null +++ b/crates/nu-path/src/path.rs @@ -0,0 +1,3095 @@ +use crate::form::{ + Absolute, Any, Canonical, IsAbsolute, MaybeRelative, PathCast, PathForm, PathJoin, PathPush, + PathSet, Relative, +}; +use std::{ + borrow::{Borrow, Cow}, + cmp::Ordering, + collections::TryReserveError, + convert::Infallible, + ffi::{OsStr, OsString}, + fmt, fs, + hash::{Hash, Hasher}, + io, + iter::FusedIterator, + marker::PhantomData, + ops::{Deref, DerefMut}, + path::StripPrefixError, + rc::Rc, + str::FromStr, + sync::Arc, +}; + +/// A wrapper around [`std::path::Path`] with extra invariants determined by its `Form`. +/// +/// The possible path forms are [`Any`], [`Relative`], [`Absolute`], or [`Canonical`]. +/// To learn more, view the documentation on [`PathForm`] or any of the individual forms. +/// +/// There are also several type aliases available, corresponding to each [`PathForm`]: +/// - [`RelativePath`] (same as [`Path`]) +/// - [`AbsolutePath`] (same as [`Path`]) +/// - [`CanonicalPath`] (same as [`Path`]) +/// +/// If the `Form` is not specified, then it defaults to [`Any`], so [`Path`] and [`Path`] +/// are one in the same. +/// +/// # Converting to [`std::path`] types +/// +/// [`Path`]s with form [`Any`] cannot be easily referenced as a [`std::path::Path`] by design. +/// Other Nushell crates need to account for the emulated current working directory +/// before passing a path to functions in [`std`] or other third party crates. +/// You can [`join`](Path::join) a [`Path`] onto an [`AbsolutePath`] or a [`CanonicalPath`]. +/// This will return an [`AbsolutePathBuf`] which can be easily referenced as a [`std::path::Path`]. +/// If you really mean it, you can instead use [`as_relative_std_path`](Path::as_relative_std_path) +/// to get the underlying [`std::path::Path`] from a [`Path`]. +/// But this may cause third-party code to use [`std::env::current_dir`] to resolve +/// the path which is almost always incorrect behavior. Extra care is needed to ensure that this +/// is not the case after using [`as_relative_std_path`](Path::as_relative_std_path). +#[repr(transparent)] +pub struct Path { + _form: PhantomData, + inner: std::path::Path, +} + +/// A path that is strictly relative. +/// +/// I.e., this path is guaranteed to never be absolute. +/// +/// [`RelativePath`]s cannot be easily converted into a [`std::path::Path`] by design. +/// Other Nushell crates need to account for the emulated current working directory +/// before passing a path to functions in [`std`] or other third party crates. +/// You can [`join`](Path::join) a [`RelativePath`] onto an [`AbsolutePath`] or a [`CanonicalPath`]. +/// This will return an [`AbsolutePathBuf`] which can be referenced as a [`std::path::Path`]. +/// If you really mean it, you can use [`as_relative_std_path`](RelativePath::as_relative_std_path) +/// to get the underlying [`std::path::Path`] from a [`RelativePath`]. +/// But this may cause third-party code to use [`std::env::current_dir`] to resolve +/// the path which is almost always incorrect behavior. Extra care is needed to ensure that this +/// is not the case after using [`as_relative_std_path`](RelativePath::as_relative_std_path). +/// +/// # Examples +/// +/// [`RelativePath`]s can be created by using [`try_relative`](Path::try_relative) +/// on a [`Path`], by using [`try_new`](Path::try_new), or by using +/// [`strip_prefix`](Path::strip_prefix) on a [`Path`] of any form. +/// +/// ``` +/// use nu_path::{Path, RelativePath}; +/// +/// let path1 = Path::new("foo.txt"); +/// let path1 = path1.try_relative().unwrap(); +/// +/// let path2 = RelativePath::try_new("foo.txt").unwrap(); +/// +/// let path3 = Path::new("/prefix/foo.txt").strip_prefix("/prefix").unwrap(); +/// +/// assert_eq!(path1, path2); +/// assert_eq!(path2, path3); +/// ``` +/// +/// You can also use `RelativePath::try_from` or `try_into`. +/// This supports attempted conversions from [`Path`] as well as types in [`std::path`]. +/// +/// ``` +/// use nu_path::{Path, RelativePath}; +/// +/// let path1 = Path::new("foo.txt"); +/// let path1: &RelativePath = path1.try_into().unwrap(); +/// +/// let path2 = std::path::Path::new("foo.txt"); +/// let path2: &RelativePath = path2.try_into().unwrap(); +/// +/// assert_eq!(path1, path2) +/// ``` +pub type RelativePath = Path; + +/// A path that is strictly absolute. +/// +/// I.e., this path is guaranteed to never be relative. +/// +/// # Examples +/// +/// [`AbsolutePath`]s can be created by using [`try_absolute`](Path::try_absolute) on a [`Path`] +/// or by using [`try_new`](AbsolutePath::try_new). +/// +#[cfg_attr(not(windows), doc = "```")] +#[cfg_attr(windows, doc = "```no_run")] +/// use nu_path::{AbsolutePath, Path}; +/// +/// let path1 = Path::new("/foo").try_absolute().unwrap(); +/// let path2 = AbsolutePath::try_new("/foo").unwrap(); +/// +/// assert_eq!(path1, path2); +/// ``` +/// +/// You can also use `AbsolutePath::try_from` or `try_into`. +/// This supports attempted conversions from [`Path`] as well as types in [`std::path`]. +/// +#[cfg_attr(not(windows), doc = "```")] +#[cfg_attr(windows, doc = "```no_run")] +/// use nu_path::{AbsolutePath, Path}; +/// +/// let path1 = Path::new("/foo"); +/// let path1: &AbsolutePath = path1.try_into().unwrap(); +/// +/// let path2 = std::path::Path::new("/foo"); +/// let path2: &AbsolutePath = path2.try_into().unwrap(); +/// +/// assert_eq!(path1, path2) +/// ``` +pub type AbsolutePath = Path; + +/// An absolute, canonical path. +/// +/// # Examples +/// +/// [`CanonicalPath`]s can only be created by using [`canonicalize`](Path::canonicalize) on +/// an [`AbsolutePath`]. References to [`CanonicalPath`]s can be converted to +/// [`AbsolutePath`] references using `as_ref`, [`cast`](Path::cast), +/// or [`as_absolute`](CanonicalPath::as_absolute). +/// +/// ```no_run +/// use nu_path::AbsolutePath; +/// +/// let path = AbsolutePath::try_new("/foo").unwrap(); +/// +/// let canonical = path.canonicalize().expect("canonicalization failed"); +/// +/// assert_eq!(path, canonical.as_absolute()); +/// ``` +pub type CanonicalPath = Path; + +impl Path { + /// Create a new path of any form without validating invariants. + #[inline] + fn new_unchecked + ?Sized>(path: &P) -> &Self { + debug_assert!(Form::invariants_satisfied(path)); + // Safety: `Path` is a repr(transparent) wrapper around `std::path::Path`. + let path = std::path::Path::new(path.as_ref()); + let ptr = std::ptr::from_ref(path) as *const Self; + unsafe { &*ptr } + } + + /// Attempt to create a new [`Path`] from a reference of another type. + /// + /// This is a convenience method instead of having to use `try_into` with a type annotation. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{AbsolutePath, RelativePath}; + /// + /// assert!(AbsolutePath::try_new("foo.txt").is_err()); + /// assert!(RelativePath::try_new("foo.txt").is_ok()); + /// ``` + #[inline] + pub fn try_new<'a, T>(path: &'a T) -> Result<&'a Self, <&'a T as TryInto<&'a Self>>::Error> + where + T: ?Sized, + &'a T: TryInto<&'a Self>, + { + path.try_into() + } + + /// Returns the underlying [`OsStr`] slice. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// let os_str = Path::new("foo.txt").as_os_str(); + /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt")); + /// ``` + #[must_use] + #[inline] + pub fn as_os_str(&self) -> &OsStr { + self.inner.as_os_str() + } + + /// Returns a [`str`] slice if the [`Path`] is valid unicode. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// let path = Path::new("foo.txt"); + /// assert_eq!(path.to_str(), Some("foo.txt")); + /// ``` + #[inline] + pub fn to_str(&self) -> Option<&str> { + self.inner.to_str() + } + + /// Converts a [`Path`] to a `Cow`. + /// + /// Any non-Unicode sequences are replaced with `U+FFFD REPLACEMENT CHARACTER`. + /// + /// # Examples + /// + /// Calling `to_string_lossy` on a [`Path`] with valid unicode: + /// + /// ``` + /// use nu_path::Path; + /// + /// let path = Path::new("foo.txt"); + /// assert_eq!(path.to_string_lossy(), "foo.txt"); + /// ``` + /// + /// Had `path` contained invalid unicode, the `to_string_lossy` call might have returned + /// `"fo�.txt"`. + #[inline] + pub fn to_string_lossy(&self) -> Cow<'_, str> { + self.inner.to_string_lossy() + } + + /// Converts a [`Path`] to an owned [`PathBuf`]. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// let path_buf = Path::new("foo.txt").to_path_buf(); + /// assert_eq!(path_buf, PathBuf::from("foo.txt")); + /// ``` + #[inline] + pub fn to_path_buf(&self) -> PathBuf { + PathBuf::new_unchecked(self.inner.to_path_buf()) + } + + /// Returns the [`Path`] without its final component, if there is one. + /// + /// This means it returns `Some("")` for relative paths with one component. + /// + /// Returns [`None`] if the path terminates in a root or prefix, or if it's + /// the empty string. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// let path = Path::new("/foo/bar"); + /// let parent = path.parent().unwrap(); + /// assert_eq!(parent, Path::new("/foo")); + /// + /// let grand_parent = parent.parent().unwrap(); + /// assert_eq!(grand_parent, Path::new("/")); + /// assert_eq!(grand_parent.parent(), None); + /// + /// let relative_path = Path::new("foo/bar"); + /// let parent = relative_path.parent(); + /// assert_eq!(parent, Some(Path::new("foo"))); + /// let grand_parent = parent.and_then(Path::parent); + /// assert_eq!(grand_parent, Some(Path::new(""))); + /// let great_grand_parent = grand_parent.and_then(Path::parent); + /// assert_eq!(great_grand_parent, None); + /// ``` + #[must_use] + #[inline] + pub fn parent(&self) -> Option<&Self> { + self.inner.parent().map(Self::new_unchecked) + } + + /// Produces an iterator over a [`Path`] and its ancestors. + /// + /// The iterator will yield the [`Path`] that is returned if the [`parent`](Path::parent) method + /// is used zero or more times. That means, the iterator will yield `&self`, + /// `&self.parent().unwrap()`, `&self.parent().unwrap().parent().unwrap()` and so on. + /// If the [`parent`](Path::parent) method returns [`None`], the iterator will do likewise. + /// The iterator will always yield at least one value, namely `&self`. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// let mut ancestors = Path::new("/foo/bar").ancestors(); + /// assert_eq!(ancestors.next(), Some(Path::new("/foo/bar"))); + /// assert_eq!(ancestors.next(), Some(Path::new("/foo"))); + /// assert_eq!(ancestors.next(), Some(Path::new("/"))); + /// assert_eq!(ancestors.next(), None); + /// + /// let mut ancestors = Path::new("../foo/bar").ancestors(); + /// assert_eq!(ancestors.next(), Some(Path::new("../foo/bar"))); + /// assert_eq!(ancestors.next(), Some(Path::new("../foo"))); + /// assert_eq!(ancestors.next(), Some(Path::new(".."))); + /// assert_eq!(ancestors.next(), Some(Path::new(""))); + /// assert_eq!(ancestors.next(), None); + /// ``` + #[inline] + pub fn ancestors(&self) -> Ancestors<'_, Form> { + Ancestors { + _form: PhantomData, + inner: self.inner.ancestors(), + } + } + + /// Returns the final component of a [`Path`], if there is one. + /// + /// If the path is a normal file, this is the file name. If it's the path of a directory, this + /// is the directory name. + /// + /// Returns [`None`] if the path terminates in `..`. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// use std::ffi::OsStr; + /// + /// assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name()); + /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name()); + /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name()); + /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name()); + /// assert_eq!(None, Path::new("foo.txt/..").file_name()); + /// assert_eq!(None, Path::new("/").file_name()); + /// ``` + #[must_use] + #[inline] + pub fn file_name(&self) -> Option<&OsStr> { + self.inner.file_name() + } + + /// Returns a relative path that, when joined onto `base`, yields `self`. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// let path = Path::new("/test/haha/foo.txt"); + /// + /// assert_eq!(path.strip_prefix("/").unwrap(), Path::new("test/haha/foo.txt")); + /// assert_eq!(path.strip_prefix("/test").unwrap(), Path::new("haha/foo.txt")); + /// assert_eq!(path.strip_prefix("/test/").unwrap(), Path::new("haha/foo.txt")); + /// assert_eq!(path.strip_prefix("/test/haha/foo.txt").unwrap(), Path::new("")); + /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/").unwrap(), Path::new("")); + /// + /// assert!(path.strip_prefix("test").is_err()); + /// assert!(path.strip_prefix("/haha").is_err()); + /// + /// let prefix = PathBuf::from("/test/"); + /// assert_eq!(path.strip_prefix(prefix).unwrap(), Path::new("haha/foo.txt")); + /// ``` + #[inline] + pub fn strip_prefix(&self, base: impl AsRef) -> Result<&RelativePath, StripPrefixError> { + self.inner + .strip_prefix(&base.as_ref().inner) + .map(RelativePath::new_unchecked) + } + + /// Determines whether `base` is a prefix of `self`. + /// + /// Only considers whole path components to match. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// let path = Path::new("/etc/passwd"); + /// + /// assert!(path.starts_with("/etc")); + /// assert!(path.starts_with("/etc/")); + /// assert!(path.starts_with("/etc/passwd")); + /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay + /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay + /// + /// assert!(!path.starts_with("/e")); + /// assert!(!path.starts_with("/etc/passwd.txt")); + /// + /// assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo")); + /// ``` + #[must_use] + #[inline] + pub fn starts_with(&self, base: impl AsRef) -> bool { + self.inner.starts_with(&base.as_ref().inner) + } + + /// Determines whether `child` is a suffix of `self`. + /// + /// Only considers whole path components to match. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// let path = Path::new("/etc/resolv.conf"); + /// + /// assert!(path.ends_with("resolv.conf")); + /// assert!(path.ends_with("etc/resolv.conf")); + /// assert!(path.ends_with("/etc/resolv.conf")); + /// + /// assert!(!path.ends_with("/resolv.conf")); + /// assert!(!path.ends_with("conf")); // use .extension() instead + /// ``` + #[must_use] + #[inline] + pub fn ends_with(&self, child: impl AsRef) -> bool { + self.inner.ends_with(&child.as_ref().inner) + } + + /// Extracts the stem (non-extension) portion of [`self.file_name`](Path::file_name). + /// + /// The stem is: + /// + /// * [`None`], if there is no file name; + /// * The entire file name if there is no embedded `.`; + /// * The entire file name if the file name begins with `.` and has no other `.`s within; + /// * Otherwise, the portion of the file name before the final `.` + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap()); + /// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap()); + /// ``` + #[must_use] + #[inline] + pub fn file_stem(&self) -> Option<&OsStr> { + self.inner.file_stem() + } + + /// Extracts the extension (without the leading dot) of [`self.file_name`](Path::file_name), + /// if possible. + /// + /// The extension is: + /// + /// * [`None`], if there is no file name; + /// * [`None`], if there is no embedded `.`; + /// * [`None`], if the file name begins with `.` and has no other `.`s within; + /// * Otherwise, the portion of the file name after the final `.` + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// assert_eq!("rs", Path::new("foo.rs").extension().unwrap()); + /// assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap()); + /// ``` + #[must_use] + #[inline] + pub fn extension(&self) -> Option<&OsStr> { + self.inner.extension() + } + + /// Produces an iterator over the [`Component`](std::path::Component)s of the path. + /// + /// When parsing the path, there is a small amount of normalization: + /// + /// * Repeated separators are ignored, so `a/b` and `a//b` both have + /// `a` and `b` as components. + /// + /// * Occurrences of `.` are normalized away, except if they are at the + /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and + /// `a/b` all have `a` and `b` as components, but `./a/b` starts with + /// an additional [`CurDir`](std::path::Component) component. + /// + /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent. + /// + /// Note that no other normalization takes place; in particular, `a/c` + /// and `a/b/../c` are distinct, to account for the possibility that `b` + /// is a symbolic link (so its parent isn't `a`). + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// use std::path::Component; + /// use std::ffi::OsStr; + /// + /// let mut components = Path::new("/tmp/foo.txt").components(); + /// + /// assert_eq!(components.next(), Some(Component::RootDir)); + /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp")))); + /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt")))); + /// assert_eq!(components.next(), None) + /// ``` + #[inline] + pub fn components(&self) -> std::path::Components<'_> { + self.inner.components() + } + + /// Produces an iterator over the path's components viewed as [`OsStr`] slices. + /// + /// For more information about the particulars of how the path is separated into components, + /// see [`components`](Path::components). + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// use std::ffi::OsStr; + /// + /// let mut it = Path::new("/tmp/foo.txt").iter(); + /// assert_eq!(it.next(), Some(OsStr::new(&std::path::MAIN_SEPARATOR.to_string()))); + /// assert_eq!(it.next(), Some(OsStr::new("tmp"))); + /// assert_eq!(it.next(), Some(OsStr::new("foo.txt"))); + /// assert_eq!(it.next(), None) + /// ``` + #[inline] + pub fn iter(&self) -> std::path::Iter<'_> { + self.inner.iter() + } + + /// Returns an object that implements [`Display`](fmt::Display) for safely printing paths + /// that may contain non-Unicode data. This may perform lossy conversion, + /// depending on the platform. If you would like an implementation which escapes the path + /// please use [`Debug`](fmt::Debug) instead. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// let path = Path::new("/tmp/foo.rs"); + /// + /// println!("{}", path.display()); + /// ``` + #[inline] + pub fn display(&self) -> std::path::Display<'_> { + self.inner.display() + } + + /// Converts a [`Box`](Box) into a [`PathBuf`] without copying or allocating. + #[inline] + pub fn into_path_buf(self: Box) -> PathBuf { + // Safety: `Path` is a repr(transparent) wrapper around `std::path::Path`. + let ptr = Box::into_raw(self) as *mut std::path::Path; + let boxed = unsafe { Box::from_raw(ptr) }; + PathBuf::new_unchecked(boxed.into_path_buf()) + } + + /// Returns a reference to the same [`Path`] in a different form. + /// + /// [`PathForm`]s can be converted to one another based on [`PathCast`] implementations. + /// Namely, the following form conversions are possible: + /// - [`Relative`], [`Absolute`], or [`Canonical`] into [`Any`]. + /// - [`Canonical`] into [`Absolute`]. + /// - Any form into itself. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, RelativePath}; + /// + /// let relative = RelativePath::try_new("test.txt").unwrap(); + /// let p: &Path = relative.cast(); + /// assert_eq!(p, relative); + /// ``` + #[inline] + pub fn cast(&self) -> &Path + where + To: PathForm, + Form: PathCast, + { + Path::new_unchecked(self) + } + + /// Returns a reference to a path with its form as [`Any`]. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, RelativePath}; + /// + /// let p = RelativePath::try_new("test.txt").unwrap(); + /// assert_eq!(Path::new("test.txt"), p.as_any()); + /// ``` + #[inline] + pub fn as_any(&self) -> &Path { + Path::new_unchecked(self) + } +} + +impl Path { + /// Create a new [`Path`] by wrapping a string slice. + /// + /// This is a cost-free conversion. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// Path::new("foo.txt"); + /// ``` + /// + /// You can create [`Path`]s from [`String`]s, or even other [`Path`]s: + /// + /// ``` + /// use nu_path::Path; + /// + /// let string = String::from("foo.txt"); + /// let from_string = Path::new(&string); + /// let from_path = Path::new(&from_string); + /// assert_eq!(from_string, from_path); + /// ``` + #[inline] + pub fn new + ?Sized>(path: &P) -> &Self { + Self::new_unchecked(path) + } + + /// Returns a mutable reference to the underlying [`OsStr`] slice. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// let mut path = PathBuf::from("Foo.TXT"); + /// + /// assert_ne!(path, Path::new("foo.txt")); + /// + /// path.as_mut_os_str().make_ascii_lowercase(); + /// assert_eq!(path, Path::new("foo.txt")); + /// ``` + #[must_use] + #[inline] + pub fn as_mut_os_str(&mut self) -> &mut OsStr { + self.inner.as_mut_os_str() + } + + /// Returns `true` if the [`Path`] is absolute, i.e., if it is independent of + /// the current directory. + /// + /// * On Unix, a path is absolute if it starts with the root, + /// so [`is_absolute`](Path::is_absolute) and [`has_root`](Path::has_root) are equivalent. + /// + /// * On Windows, a path is absolute if it has a prefix and starts with the root: + /// `c:\windows` is absolute, while `c:temp` and `\temp` are not. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// assert!(!Path::new("foo.txt").is_absolute()); + /// ``` + #[must_use] + #[inline] + pub fn is_absolute(&self) -> bool { + self.inner.is_absolute() + } + + // Returns `true` if the [`Path`] is relative, i.e., not absolute. + /// + /// See [`is_absolute`](Path::is_absolute)'s documentation for more details. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// assert!(Path::new("foo.txt").is_relative()); + /// ``` + #[must_use] + #[inline] + pub fn is_relative(&self) -> bool { + self.inner.is_relative() + } + + /// Returns an `Ok` [`AbsolutePath`] if the [`Path`] is absolute. + /// Otherwise, returns an `Err` [`RelativePath`]. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// assert!(Path::new("test.txt").try_absolute().is_err()); + /// ``` + #[inline] + pub fn try_absolute(&self) -> Result<&AbsolutePath, &RelativePath> { + if self.is_absolute() { + Ok(AbsolutePath::new_unchecked(&self.inner)) + } else { + Err(RelativePath::new_unchecked(&self.inner)) + } + } + + /// Returns an `Ok` [`RelativePath`] if the [`Path`] is relative. + /// Otherwise, returns an `Err` [`AbsolutePath`]. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// assert!(Path::new("test.txt").try_relative().is_ok()); + /// ``` + #[inline] + pub fn try_relative(&self) -> Result<&RelativePath, &AbsolutePath> { + if self.is_relative() { + Ok(RelativePath::new_unchecked(&self.inner)) + } else { + Err(AbsolutePath::new_unchecked(&self.inner)) + } + } +} + +impl Path { + /// Creates an owned [`PathBuf`] with `path` adjoined to `self`. + /// + /// If `path` is absolute, it replaces the current path. + /// + /// See [`PathBuf::push`] for more details on what it means to adjoin a path. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd")); + /// assert_eq!(Path::new("/etc").join("/bin/sh"), PathBuf::from("/bin/sh")); + /// ``` + #[must_use] + #[inline] + pub fn join(&self, path: impl AsRef) -> PathBuf { + PathBuf::new_unchecked(self.inner.join(&path.as_ref().inner)) + } +} + +impl Path { + /// Creates an owned [`PathBuf`] like `self` but with the given file name. + /// + /// See [`PathBuf::set_file_name`] for more details. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// let path = Path::new("/tmp/foo.png"); + /// assert_eq!(path.with_file_name("bar"), PathBuf::from("/tmp/bar")); + /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt")); + /// + /// let path = Path::new("/tmp"); + /// assert_eq!(path.with_file_name("var"), PathBuf::from("/var")); + /// ``` + #[inline] + pub fn with_file_name(&self, file_name: impl AsRef) -> PathBuf { + PathBuf::new_unchecked(self.inner.with_file_name(file_name)) + } + + /// Creates an owned [`PathBuf`] like `self` but with the given extension. + /// + /// See [`PathBuf::set_extension`] for more details. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// let path = Path::new("foo.rs"); + /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt")); + /// + /// let path = Path::new("foo.tar.gz"); + /// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar")); + /// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz")); + /// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt")); + /// ``` + #[inline] + pub fn with_extension(&self, extension: impl AsRef) -> PathBuf { + PathBuf::new_unchecked(self.inner.with_extension(extension)) + } +} + +impl Path { + /// Returns the, potentially relative, underlying [`std::path::Path`]. + /// + /// # Note + /// + /// Caution should be taken when using this function. Nushell keeps track of an emulated current + /// working directory, and using the [`std::path::Path`] returned from this method will likely + /// use [`std::env::current_dir`] to resolve the path instead of using the emulated current + /// working directory. + /// + /// Instead, you should probably join this path onto the emulated current working directory. + /// Any [`AbsolutePath`] or [`CanonicalPath`] will also suffice. + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// let p = Path::new("test.txt"); + /// assert_eq!(std::path::Path::new("test.txt"), p.as_relative_std_path()); + /// ``` + #[inline] + pub fn as_relative_std_path(&self) -> &std::path::Path { + &self.inner + } + + // Returns `true` if the [`Path`] has a root. + /// + /// * On Unix, a path has a root if it begins with `/`. + /// + /// * On Windows, a path has a root if it: + /// * has no prefix and begins with a separator, e.g., `\windows` + /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows` + /// * has any non-disk prefix, e.g., `\\server\share` + /// + /// # Examples + /// + /// ``` + /// use nu_path::Path; + /// + /// assert!(Path::new("/etc/passwd").has_root()); + /// ``` + #[must_use] + #[inline] + pub fn has_root(&self) -> bool { + self.inner.has_root() + } +} + +impl Path { + /// Returns the underlying [`std::path::Path`]. + /// + /// # Examples + /// + #[cfg_attr(not(windows), doc = "```")] + #[cfg_attr(windows, doc = "```no_run")] + /// use nu_path::AbsolutePath; + /// + /// let p = AbsolutePath::try_new("/test").unwrap(); + /// assert_eq!(std::path::Path::new("/test"), p.as_std_path()); + /// ``` + #[inline] + pub fn as_std_path(&self) -> &std::path::Path { + &self.inner + } + + /// Converts a [`Path`] to an owned [`std::path::PathBuf`]. + /// + /// # Examples + /// + #[cfg_attr(not(windows), doc = "```")] + #[cfg_attr(windows, doc = "```no_run")] + /// use nu_path::AbsolutePath; + /// + /// let path = AbsolutePath::try_new("/foo").unwrap(); + /// assert_eq!(path.to_std_path_buf(), std::path::PathBuf::from("/foo")); + /// ``` + #[inline] + pub fn to_std_path_buf(&self) -> std::path::PathBuf { + self.inner.to_path_buf() + } + + /// Queries the file system to get information about a file, directory, etc. + /// + /// This function will traverse symbolic links to query information about the destination file. + /// + /// This is an alias to [`std::fs::metadata`]. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePath; + /// + /// let path = AbsolutePath::try_new("/Minas/tirith").unwrap(); + /// let metadata = path.metadata().expect("metadata call failed"); + /// println!("{:?}", metadata.file_type()); + /// ``` + #[inline] + pub fn metadata(&self) -> io::Result { + self.inner.metadata() + } + + /// Returns an iterator over the entries within a directory. + /// + /// The iterator will yield instances of [io::Result]<[fs::DirEntry]>. + /// New errors may be encountered after an iterator is initially constructed. + /// + /// This is an alias to [`std::fs::read_dir`]. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePath; + /// + /// let path = AbsolutePath::try_new("/laputa").unwrap(); + /// for entry in path.read_dir().expect("read_dir call failed") { + /// if let Ok(entry) = entry { + /// println!("{:?}", entry.path()); + /// } + /// } + /// ``` + #[inline] + pub fn read_dir(&self) -> io::Result { + self.inner.read_dir() + } + + /// Returns `true` if the path points at an existing entity. + /// + /// Warning: this method may be error-prone, consider using [`try_exists`](Path::try_exists) + /// instead! It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs. + /// + /// This function will traverse symbolic links to query information about the destination file. + /// + /// If you cannot access the metadata of the file, e.g. because of a permission error + /// or broken symbolic links, this will return `false`. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePath; + /// + /// let path = AbsolutePath::try_new("/does_not_exist").unwrap(); + /// assert!(!path.exists()); + /// ``` + #[must_use] + #[inline] + pub fn exists(&self) -> bool { + self.inner.exists() + } + + /// Returns `true` if the path exists on disk and is pointing at a regular file. + /// + /// This function will traverse symbolic links to query information about the destination file. + /// + /// If you cannot access the metadata of the file, e.g. because of a permission error + /// or broken symbolic links, this will return `false`. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePath; + /// + /// let path = AbsolutePath::try_new("/is_a_directory/").unwrap(); + /// assert_eq!(path.is_file(), false); + /// + /// let path = AbsolutePath::try_new("/a_file.txt").unwrap(); + /// assert_eq!(path.is_file(), true); + /// ``` + /// + /// # See Also + /// + /// When the goal is simply to read from (or write to) the source, the most reliable way + /// to test the source can be read (or written to) is to open it. Only using `is_file` can + /// break workflows like `diff <( prog_a )` on a Unix-like system for example. + /// See [`std::fs::File::open`] or [`std::fs::OpenOptions::open`] for more information. + #[must_use] + #[inline] + pub fn is_file(&self) -> bool { + self.inner.is_file() + } + + /// Returns `true` if the path exists on disk and is pointing at a directory. + /// + /// This function will traverse symbolic links to query information about the destination file. + /// + /// If you cannot access the metadata of the file, e.g. because of a permission error + /// or broken symbolic links, this will return `false`. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePath; + /// + /// let path = AbsolutePath::try_new("/is_a_directory/").unwrap(); + /// assert_eq!(path.is_dir(), true); + /// + /// let path = AbsolutePath::try_new("/a_file.txt").unwrap(); + /// assert_eq!(path.is_dir(), false); + /// ``` + #[must_use] + #[inline] + pub fn is_dir(&self) -> bool { + self.inner.is_dir() + } +} + +impl AbsolutePath { + /// Returns the canonical, absolute form of the path with all intermediate components + /// normalized and symbolic links resolved. + /// + /// On Windows, this will also simplify to a winuser path. + /// + /// This is an alias to [`std::fs::canonicalize`]. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::{AbsolutePath, PathBuf}; + /// + /// let path = AbsolutePath::try_new("/foo/test/../test/bar.rs").unwrap(); + /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs")); + /// ``` + #[cfg(not(windows))] + #[inline] + pub fn canonicalize(&self) -> io::Result { + self.inner + .canonicalize() + .map(CanonicalPathBuf::new_unchecked) + } + + /// Returns the canonical, absolute form of the path with all intermediate components + /// normalized and symbolic links resolved. + /// + /// On Windows, this will also simplify to a winuser path. + /// + /// This is an alias to [`std::fs::canonicalize`]. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::{AbsolutePath, PathBuf}; + /// + /// let path = AbsolutePath::try_new("/foo/test/../test/bar.rs").unwrap(); + /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs")); + /// ``` + #[cfg(windows)] + pub fn canonicalize(&self) -> io::Result { + use omnipath::WinPathExt; + + let path = self.inner.canonicalize()?.to_winuser_path()?; + Ok(CanonicalPathBuf::new_unchecked(path)) + } + + /// Reads a symbolic link, returning the file that the link points to. + /// + /// This is an alias to [`std::fs::read_link`]. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePath; + /// + /// let path = AbsolutePath::try_new("/laputa/sky_castle.rs").unwrap(); + /// let path_link = path.read_link().expect("read_link call failed"); + /// ``` + #[inline] + pub fn read_link(&self) -> io::Result { + self.inner.read_link().map(PathBuf::new_unchecked) + } + + /// Returns `Ok(true)` if the path points at an existing entity. + /// + /// This function will traverse symbolic links to query information about the destination file. + /// In case of broken symbolic links this will return `Ok(false)`. + /// + /// [`Path::exists`] only checks whether or not a path was both found and readable. + /// By contrast, [`try_exists`](Path::try_exists) will return `Ok(true)` or `Ok(false)`, + /// respectively, if the path was _verified_ to exist or not exist. + /// If its existence can neither be confirmed nor denied, it will propagate an `Err` instead. + /// This can be the case if e.g. listing permission is denied on one of the parent directories. + /// + /// Note that while this avoids some pitfalls of the [`exists`](Path::exists) method, + /// it still can not prevent time-of-check to time-of-use (TOCTOU) bugs. + /// You should only use it in scenarios where those bugs are not an issue. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePath; + /// + /// let path = AbsolutePath::try_new("/does_not_exist").unwrap(); + /// assert!(!path.try_exists().unwrap()); + /// + /// let path = AbsolutePath::try_new("/root/secret_file.txt").unwrap(); + /// assert!(path.try_exists().is_err()); + /// ``` + #[inline] + pub fn try_exists(&self) -> io::Result { + self.inner.try_exists() + } + + /// Returns `true` if the path exists on disk and is pointing at a symbolic link. + /// + /// This function will not traverse symbolic links. + /// In case of a broken symbolic link this will also return true. + /// + /// If you cannot access the directory containing the file, e.g., because of a permission error, + /// this will return false. + /// + /// # Examples + /// + #[cfg_attr(unix, doc = "```no_run")] + #[cfg_attr(not(unix), doc = "```ignore")] + /// use nu_path::AbsolutePath; + /// use std::os::unix::fs::symlink; + /// + /// let link_path = AbsolutePath::try_new("/link").unwrap(); + /// symlink("/origin_does_not_exist/", link_path).unwrap(); + /// assert_eq!(link_path.is_symlink(), true); + /// assert_eq!(link_path.exists(), false); + /// ``` + #[must_use] + #[inline] + pub fn is_symlink(&self) -> bool { + self.inner.is_symlink() + } + + /// Queries the metadata about a file without following symlinks. + /// + /// This is an alias to [`std::fs::symlink_metadata`]. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePath; + /// + /// let path = AbsolutePath::try_new("/Minas/tirith").unwrap(); + /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed"); + /// println!("{:?}", metadata.file_type()); + /// ``` + #[inline] + pub fn symlink_metadata(&self) -> io::Result { + self.inner.symlink_metadata() + } +} + +impl CanonicalPath { + /// Returns a [`CanonicalPath`] as a [`AbsolutePath`]. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePath; + /// + /// let absolute = AbsolutePath::try_new("/test").unwrap(); + /// let p = absolute.canonicalize().unwrap(); + /// assert_eq!(absolute, p.as_absolute()); + /// ``` + #[inline] + pub fn as_absolute(&self) -> &AbsolutePath { + self.cast() + } +} + +impl fmt::Debug for Path { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.inner, fmt) + } +} + +impl Clone for Box> { + #[inline] + fn clone(&self) -> Self { + std_box_to_box(self.inner.into()) + } +} + +impl ToOwned for Path { + type Owned = PathBuf; + + #[inline] + fn to_owned(&self) -> Self::Owned { + self.to_path_buf() + } + + #[inline] + fn clone_into(&self, target: &mut PathBuf) { + self.inner.clone_into(&mut target.inner); + } +} + +impl<'a, Form: PathForm> IntoIterator for &'a Path { + type Item = &'a OsStr; + + type IntoIter = std::path::Iter<'a>; + + #[inline] + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +/// An iterator over [`Path`] and its ancestors. +/// +/// This `struct` is created by the [`ancestors`](Path::ancestors) method on [`Path`]. +/// See its documentation for more. +/// +/// # Examples +/// +/// ``` +/// use nu_path::Path; +/// +/// let path = Path::new("/foo/bar"); +/// +/// for ancestor in path.ancestors() { +/// println!("{}", ancestor.display()); +/// } +/// ``` +#[derive(Clone, Copy)] +pub struct Ancestors<'a, Form: PathForm> { + _form: PhantomData, + inner: std::path::Ancestors<'a>, +} + +impl fmt::Debug for Ancestors<'_, Form> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.inner, f) + } +} + +impl<'a, Form: PathForm> Iterator for Ancestors<'a, Form> { + type Item = &'a Path; + + fn next(&mut self) -> Option { + self.inner.next().map(Path::new_unchecked) + } +} + +impl FusedIterator for Ancestors<'_, Form> {} + +/// A wrapper around [`std::path::PathBuf`] with extra invariants determined by its `Form`. +/// +/// The possible path forms are [`Any`], [`Relative`], [`Absolute`], or [`Canonical`]. +/// To learn more, view the documentation on [`PathForm`] or any of the individual forms. +/// +/// There are also several type aliases available, corresponding to each [`PathForm`]: +/// - [`RelativePathBuf`] (same as [`PathBuf`]) +/// - [`AbsolutePathBuf`] (same as [`PathBuf`]) +/// - [`CanonicalPathBuf`] (same as [`PathBuf`]) +/// +/// If the `Form` is not specified, then it defaults to [`Any`], +/// so [`PathBuf`] and [`PathBuf`] are one in the same. +/// +/// # Examples +/// +/// To create a [`PathBuf`] with [`Any`] form, you can use the same techniques as when creating +/// a [`std::path::PathBuf`]. +/// +/// ``` +/// use nu_path::PathBuf; +/// +/// let path = PathBuf::from(r"C:\windows\system32.dll"); +/// +/// let mut path1 = PathBuf::new(); +/// path1.push(r"C:\"); +/// path1.push("windows"); +/// path1.push("system32"); +/// path1.set_extension("dll"); +/// +/// let path2: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect(); +/// +/// assert_eq!(path1, path2); +/// ``` +/// +/// # Converting to [`std::path`] types +/// +/// [`PathBuf`]s with form [`Any`] cannot be easily referenced as a [`std::path::Path`] +/// or converted to a [`std::path::PathBuf`] by design. +/// Other Nushell crates need to account for the emulated current working directory +/// before passing a path to functions in [`std`] or other third party crates. +/// You can [`join`](Path::join) a [`Path`] onto an [`AbsolutePath`] or a [`CanonicalPath`]. +/// This will return an [`AbsolutePathBuf`] which can be easily referenced as a [`std::path::Path`]. +/// If you really mean it, you can instead use [`as_relative_std_path`](Path::as_relative_std_path) +/// or [`into_relative_std_path_buf`](PathBuf::into_relative_std_path_buf) +/// to get the underlying [`std::path::Path`] or [`std::path::PathBuf`] from a [`PathBuf`]. +/// But this may cause third-party code to use [`std::env::current_dir`] to resolve +/// the path which is almost always incorrect behavior. Extra care is needed to ensure that this +/// is not the case after using [`as_relative_std_path`](Path::as_relative_std_path) +/// or [`into_relative_std_path_buf`](PathBuf::into_relative_std_path_buf). +#[repr(transparent)] +pub struct PathBuf { + _form: PhantomData, + inner: std::path::PathBuf, +} + +/// A path buf that is strictly relative. +/// +/// I.e., this path buf is guaranteed to never be absolute. +/// +/// [`RelativePathBuf`]s cannot be easily referenced as a [`std::path::Path`] +/// or converted to a [`std::path::PathBuf`] by design. +/// Other Nushell crates need to account for the emulated current working directory +/// before passing a path to functions in [`std`] or other third party crates. +/// You can [`join`](Path::join) a [`RelativePath`] onto an [`AbsolutePath`] or a [`CanonicalPath`]. +/// This will return an [`AbsolutePathBuf`] which can be easily referenced as a [`std::path::Path`]. +/// If you really mean it, you can instead use +/// [`as_relative_std_path`](RelativePath::as_relative_std_path) +/// or [`into_relative_std_path_buf`](RelativePathBuf::into_relative_std_path_buf) +/// to get the underlying [`std::path::Path`] or [`std::path::PathBuf`] from a [`RelativePathBuf`]. +/// But this may cause third-party code to use [`std::env::current_dir`] to resolve +/// the path which is almost always incorrect behavior. Extra care is needed to ensure that this +/// is not the case after using [`as_relative_std_path`](RelativePath::as_relative_std_path) +/// or [`into_relative_std_path_buf`](RelativePathBuf::into_relative_std_path_buf). +/// +/// # Examples +/// +/// [`RelativePathBuf`]s can be created by using [`try_into_relative`](PathBuf::try_into_relative) +/// on a [`PathBuf`] or by using [`to_path_buf`](Path::to_path_buf) on a [`RelativePath`]. +/// +/// ``` +/// use nu_path::{PathBuf, RelativePath, RelativePathBuf}; +/// +/// let path_buf = PathBuf::from("foo.txt"); +/// let path_buf = path_buf.try_into_relative().unwrap(); +/// +/// let path = RelativePath::try_new("foo.txt").unwrap(); +/// let path_buf2 = path.to_path_buf(); +/// +/// assert_eq!(path_buf, path_buf2); +/// ``` +/// +/// You can also use `RelativePathBuf::try_from` or `try_into`. +/// This supports attempted conversions from [`Path`] as well as types in [`std::path`]. +/// +/// ``` +/// use nu_path::{Path, RelativePathBuf}; +/// +/// let path1 = RelativePathBuf::try_from("foo.txt").unwrap(); +/// +/// let path2 = Path::new("foo.txt"); +/// let path2 = RelativePathBuf::try_from(path2).unwrap(); +/// +/// let path3 = std::path::PathBuf::from("foo.txt"); +/// let path3: RelativePathBuf = path3.try_into().unwrap(); +/// +/// assert_eq!(path1, path2); +/// assert_eq!(path2, path3); +/// ``` +pub type RelativePathBuf = PathBuf; + +/// A path buf that is strictly absolute. +/// +/// I.e., this path buf is guaranteed to never be relative. +/// +/// # Examples +/// +/// [`AbsolutePathBuf`]s can be created by using [`try_into_absolute`](PathBuf::try_into_absolute) +/// on a [`PathBuf`] or by using [`to_path_buf`](Path::to_path_buf) on an [`AbsolutePath`]. +/// +#[cfg_attr(not(windows), doc = "```")] +#[cfg_attr(windows, doc = "```no_run")] +/// use nu_path::{AbsolutePath, AbsolutePathBuf, PathBuf}; +/// +/// let path_buf1 = PathBuf::from("/foo"); +/// let path_buf1 = path_buf1.try_into_absolute().unwrap(); +/// +/// let path = AbsolutePath::try_new("/foo").unwrap(); +/// let path_buf2 = path.to_path_buf(); +/// +/// assert_eq!(path_buf1, path_buf2); +/// ``` +/// +/// You can also use `AbsolutePathBuf::try_from` or `try_into`. +/// This supports attempted conversions from [`Path`] as well as types in [`std::path`]. +/// +#[cfg_attr(not(windows), doc = "```")] +#[cfg_attr(windows, doc = "```no_run")] +/// use nu_path::{AbsolutePathBuf, Path}; +/// +/// let path1 = AbsolutePathBuf::try_from("/foo").unwrap(); +/// +/// let path2 = Path::new("/foo"); +/// let path2 = AbsolutePathBuf::try_from(path2).unwrap(); +/// +/// let path3 = std::path::PathBuf::from("/foo"); +/// let path3: AbsolutePathBuf = path3.try_into().unwrap(); +/// +/// assert_eq!(path1, path2); +/// assert_eq!(path2, path3); +/// ``` +pub type AbsolutePathBuf = PathBuf; + +/// An absolute, canonical path buf. +/// +/// # Examples +/// +/// [`CanonicalPathBuf`]s can only be created by using [`canonicalize`](Path::canonicalize) on +/// an [`AbsolutePath`]. [`CanonicalPathBuf`]s can be converted back to [`AbsolutePathBuf`]s via +/// [`into_absolute`](CanonicalPathBuf::into_absolute). +/// +/// ```no_run +/// use nu_path::AbsolutePathBuf; +/// +/// let path = AbsolutePathBuf::try_from("/foo").unwrap(); +/// +/// let canonical = path.canonicalize().expect("canonicalization failed"); +/// +/// assert_eq!(path, canonical.into_absolute()); +/// ``` +pub type CanonicalPathBuf = PathBuf; + +impl PathBuf { + /// Create a new [`PathBuf`] of any form without validiting invariants. + #[inline] + pub(crate) fn new_unchecked(buf: std::path::PathBuf) -> Self { + debug_assert!(Form::invariants_satisfied(&buf)); + Self { + _form: PhantomData, + inner: buf, + } + } + + /// Coerces to a [`Path`] slice. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// let p = PathBuf::from("/test"); + /// assert_eq!(Path::new("/test"), p.as_path()); + /// ``` + #[must_use] + #[inline] + pub fn as_path(&self) -> &Path { + Path::new_unchecked(&self.inner) + } + + /// Truncates `self` to [`self.parent`](Path::parent). + /// + /// Returns `false` and does nothing if [`self.parent`](Path::parent) is [`None`]. + /// Otherwise, returns `true`. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// let mut p = PathBuf::from("/spirited/away.rs"); + /// + /// p.pop(); + /// assert_eq!(Path::new("/spirited"), p); + /// p.pop(); + /// assert_eq!(Path::new("/"), p); + /// ``` + #[inline] + pub fn pop(&mut self) -> bool { + self.inner.pop() + } + + /// Consumes the [`PathBuf`], returning its internal [`OsString`] storage. + /// + /// # Examples + /// + /// ``` + /// use nu_path::PathBuf; + /// + /// let p = PathBuf::from("/the/head"); + /// let os_str = p.into_os_string(); + /// ``` + #[inline] + pub fn into_os_string(self) -> OsString { + self.inner.into_os_string() + } + + /// Converts this [`PathBuf`] into a [boxed](Box) [`Path`]. + #[inline] + pub fn into_boxed_path(self) -> Box> { + std_box_to_box(self.inner.into_boxed_path()) + } + + /// Returns the [`capacity`](OsString::capacity) of the underlying [`OsString`]. + #[must_use] + #[inline] + pub fn capacity(&self) -> usize { + self.inner.capacity() + } + + /// Invokes [`reserve`](OsString::reserve) on the underlying [`OsString`]. + #[inline] + pub fn reserve(&mut self, additional: usize) { + self.inner.reserve(additional) + } + + /// Invokes [`try_reserve`](OsString::try_reserve) on the underlying [`OsString`]. + #[inline] + pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.inner.try_reserve(additional) + } + + /// Invokes [`reserve_exact`](OsString::reserve_exact) on the underlying [`OsString`]. + #[inline] + pub fn reserve_exact(&mut self, additional: usize) { + self.inner.reserve_exact(additional) + } + + /// Invokes [`try_reserve_exact`](OsString::try_reserve_exact) on the underlying [`OsString`]. + #[inline] + pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.inner.try_reserve_exact(additional) + } + + /// Invokes [`shrink_to_fit`](OsString::shrink_to_fit) on the underlying [`OsString`]. + #[inline] + pub fn shrink_to_fit(&mut self) { + self.inner.shrink_to_fit() + } + + /// Invokes [`shrink_to`](OsString::shrink_to) on the underlying [`OsString`]. + #[inline] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.inner.shrink_to(min_capacity) + } + + /// Consumes a [`PathBuf`], returning it with a different form. + /// + /// [`PathForm`]s can be converted to one another based on [`PathCast`] implementations. + /// Namely, the following form conversions are possible: + /// - [`Relative`], [`Absolute`], or [`Canonical`] into [`Any`]. + /// - [`Canonical`] into [`Absolute`]. + /// - Any form into itself. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{PathBuf, RelativePathBuf}; + /// + /// let p = RelativePathBuf::try_from("test.txt").unwrap(); + /// let p: PathBuf = p.cast_into(); + /// assert_eq!(PathBuf::from("test.txt"), p); + /// ``` + #[inline] + pub fn cast_into(self) -> PathBuf + where + To: PathForm, + Form: PathCast, + { + PathBuf::new_unchecked(self.inner) + } + + /// Consumes a [`PathBuf`], returning it with form [`Any`]. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{PathBuf, RelativePathBuf}; + /// + /// let p = RelativePathBuf::try_from("test.txt").unwrap(); + /// assert_eq!(PathBuf::from("test.txt"), p.into_any()); + /// ``` + #[inline] + pub fn into_any(self) -> PathBuf { + PathBuf::new_unchecked(self.inner) + } +} + +impl PathBuf { + /// Creates an empty [`PathBuf`]. + /// + /// # Examples + /// + /// ``` + /// use nu_path::PathBuf; + /// + /// let path = PathBuf::new(); + /// ``` + #[must_use] + #[inline] + pub fn new() -> Self { + Self::new_unchecked(std::path::PathBuf::new()) + } + + /// Creates a new [`PathBuf`] with a given capacity used to create the internal [`OsString`]. + /// See [`with_capacity`](OsString::with_capacity) defined on [`OsString`]. + /// + /// # Examples + /// + /// ``` + /// use nu_path::PathBuf; + /// + /// let mut path = PathBuf::with_capacity(10); + /// let capacity = path.capacity(); + /// + /// // This push is done without reallocating + /// path.push(r"C:\"); + /// + /// assert_eq!(capacity, path.capacity()); + /// ``` + #[inline] + #[must_use] + pub fn with_capacity(capacity: usize) -> Self { + Self::new_unchecked(std::path::PathBuf::with_capacity(capacity)) + } + + /// Returns a mutable reference to the underlying [`OsString`]. + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// let mut path = PathBuf::from("/foo"); + /// + /// path.push("bar"); + /// assert_eq!(path, Path::new("/foo/bar")); + /// + /// // OsString's `push` does not add a separator. + /// path.as_mut_os_string().push("baz"); + /// assert_eq!(path, Path::new("/foo/barbaz")); + /// ``` + #[must_use] + #[inline] + pub fn as_mut_os_string(&mut self) -> &mut OsString { + self.inner.as_mut_os_string() + } + + /// Invokes [`clear`](OsString::clear) on the underlying [`OsString`]. + #[inline] + pub fn clear(&mut self) { + self.inner.clear() + } + + /// Consumes a [`PathBuf`], returning an `Ok` [`RelativePathBuf`] if the [`PathBuf`] + /// is relative. Otherwise, returns the original [`PathBuf`] as an `Err`. + /// + /// # Examples + /// + /// ``` + /// use nu_path::PathBuf; + /// + /// assert!(PathBuf::from("test.txt").try_into_relative().is_ok()); + /// ``` + #[inline] + pub fn try_into_relative(self) -> Result { + if self.inner.is_relative() { + Ok(PathBuf::new_unchecked(self.inner)) + } else { + Err(self) + } + } + + /// Consumes a [`PathBuf`], returning an `Ok` [`AbsolutePathBuf`] if the [`PathBuf`] + /// is absolute. Otherwise, returns the original [`PathBuf`] as an `Err`. + /// + /// # Examples + /// + /// ``` + /// use nu_path::PathBuf; + /// + /// assert!(PathBuf::from("test.txt").try_into_absolute().is_err()); + /// ``` + #[inline] + pub fn try_into_absolute(self) -> Result { + if self.inner.is_absolute() { + Ok(PathBuf::new_unchecked(self.inner)) + } else { + Err(self) + } + } +} + +impl PathBuf { + /// Extends `self` with `path`. + /// + /// If `path` is absolute, it replaces the current path. + /// + /// On Windows: + /// + /// * if `path` has a root but no prefix (e.g., `\windows`), it + /// replaces everything except for the prefix (if any) of `self`. + /// * if `path` has a prefix but no root, it replaces `self`. + /// * if `self` has a verbatim prefix (e.g. `\\?\C:\windows`) + /// and `path` is not empty, the new path is normalized: all references + /// to `.` and `..` are removed. + /// + /// Consider using [`Path::join`] if you need a new [`PathBuf`] instead of + /// using this function on a cloned [`PathBuf`]. + /// + /// # Examples + /// + /// Pushing a relative path extends the existing path: + /// + /// ``` + /// use nu_path::PathBuf; + /// + /// let mut path = PathBuf::from("/tmp"); + /// path.push("file.bk"); + /// assert_eq!(path, PathBuf::from("/tmp/file.bk")); + /// ``` + /// + /// Pushing an absolute path replaces the existing path: + /// + /// ``` + /// use nu_path::PathBuf; + /// + /// let mut path = PathBuf::from("/tmp"); + /// path.push("/etc"); + /// assert_eq!(path, PathBuf::from("/etc")); + /// ``` + #[inline] + pub fn push(&mut self, path: impl AsRef) { + self.inner.push(&path.as_ref().inner) + } +} + +impl PathBuf { + /// Updates [`self.file_name`](Path::file_name) to `file_name`. + /// + /// If [`self.file_name`](Path::file_name) was [`None`], + /// this is equivalent to pushing `file_name`. + /// + /// Otherwise it is equivalent to calling [`pop`](PathBuf::pop) and then pushing `file_name`. + /// The new path will be a sibling of the original path. + /// (That is, it will have the same parent.) + /// + /// # Examples + /// + /// ``` + /// use nu_path::PathBuf; + /// + /// let mut buf = PathBuf::from("/"); + /// assert!(buf.file_name() == None); + /// + /// buf.set_file_name("foo.txt"); + /// assert!(buf == PathBuf::from("/foo.txt")); + /// assert!(buf.file_name().is_some()); + /// + /// buf.set_file_name("bar.txt"); + /// assert!(buf == PathBuf::from("/bar.txt")); + /// + /// buf.set_file_name("baz"); + /// assert!(buf == PathBuf::from("/baz")); + /// ``` + #[inline] + pub fn set_file_name(&mut self, file_name: impl AsRef) { + self.inner.set_file_name(file_name) + } + + /// Updates [`self.extension`](Path::extension) to `Some(extension)` or to [`None`] if + /// `extension` is empty. + /// + /// Returns `false` and does nothing if [`self.file_name`](Path::file_name) is [`None`], + /// returns `true` and updates the extension otherwise. + /// + /// If [`self.extension`](Path::extension) is [`None`], the extension is added; otherwise + /// it is replaced. + /// + /// If `extension` is the empty string, [`self.extension`](Path::extension) will be [`None`] + /// afterwards, not `Some("")`. + /// + /// # Caveats + /// + /// The new `extension` may contain dots and will be used in its entirety, + /// but only the part after the final dot will be reflected in + /// [`self.extension`](Path::extension). + /// + /// If the file stem contains internal dots and `extension` is empty, part of the + /// old file stem will be considered the new [`self.extension`](Path::extension). + /// + /// # Examples + /// + /// ``` + /// use nu_path::{Path, PathBuf}; + /// + /// let mut p = PathBuf::from("/feel/the"); + /// + /// p.set_extension("force"); + /// assert_eq!(Path::new("/feel/the.force"), p.as_path()); + /// + /// p.set_extension("dark.side"); + /// assert_eq!(Path::new("/feel/the.dark.side"), p.as_path()); + /// + /// p.set_extension("cookie"); + /// assert_eq!(Path::new("/feel/the.dark.cookie"), p.as_path()); + /// + /// p.set_extension(""); + /// assert_eq!(Path::new("/feel/the.dark"), p.as_path()); + /// + /// p.set_extension(""); + /// assert_eq!(Path::new("/feel/the"), p.as_path()); + /// + /// p.set_extension(""); + /// assert_eq!(Path::new("/feel/the"), p.as_path()); + /// ``` + #[inline] + pub fn set_extension(&mut self, extension: impl AsRef) -> bool { + self.inner.set_extension(extension) + } +} + +impl PathBuf { + /// Consumes a [`PathBuf`] and returns the, potentially relative, + /// underlying [`std::path::PathBuf`]. + /// + /// # Note + /// + /// Caution should be taken when using this function. Nushell keeps track of an emulated current + /// working directory, and using the [`std::path::PathBuf`] returned from this method + /// will likely use [`std::env::current_dir`] to resolve the path instead of + /// using the emulated current working directory. + /// + /// Instead, you should probably join this path onto the emulated current working directory. + /// Any [`AbsolutePath`] or [`CanonicalPath`] will also suffice. + /// + /// # Examples + /// + /// ``` + /// use nu_path::PathBuf; + /// + /// let p = PathBuf::from("test.txt"); + /// assert_eq!(std::path::PathBuf::from("test.txt"), p.into_relative_std_path_buf()); + /// ``` + #[inline] + pub fn into_relative_std_path_buf(self) -> std::path::PathBuf { + self.inner + } +} + +impl PathBuf { + /// Consumes a [`PathBuf`] and returns the underlying [`std::path::PathBuf`]. + /// + /// # Examples + /// + #[cfg_attr(not(windows), doc = "```")] + #[cfg_attr(windows, doc = "```no_run")] + /// use nu_path::AbsolutePathBuf; + /// + /// let p = AbsolutePathBuf::try_from("/test").unwrap(); + /// assert_eq!(std::path::PathBuf::from("/test"), p.into_std_path_buf()); + /// ``` + #[inline] + pub fn into_std_path_buf(self) -> std::path::PathBuf { + self.inner + } +} + +impl CanonicalPathBuf { + /// Consumes a [`CanonicalPathBuf`] and returns an [`AbsolutePathBuf`]. + /// + /// # Examples + /// + /// ```no_run + /// use nu_path::AbsolutePathBuf; + /// + /// let absolute = AbsolutePathBuf::try_from("/test").unwrap(); + /// let p = absolute.canonicalize().unwrap(); + /// assert_eq!(absolute, p.into_absolute()); + /// ``` + #[inline] + pub fn into_absolute(self) -> AbsolutePathBuf { + self.cast_into() + } +} + +impl Default for PathBuf { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl Clone for PathBuf { + #[inline] + fn clone(&self) -> Self { + Self { + _form: PhantomData, + inner: self.inner.clone(), + } + } +} + +impl fmt::Debug for PathBuf { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Deref for PathBuf { + type Target = Path; + + #[inline] + fn deref(&self) -> &Self::Target { + self.as_path() + } +} + +impl DerefMut for PathBuf { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + // Safety: `Path` is a repr(transparent) wrapper around `std::path::Path`. + let path: &mut std::path::Path = &mut self.inner; + let ptr = std::ptr::from_mut(path) as *mut Path; + unsafe { &mut *ptr } + } +} + +impl, To: PathForm> Borrow> for PathBuf { + #[inline] + fn borrow(&self) -> &Path { + self.cast() + } +} + +impl Borrow for PathBuf { + #[inline] + fn borrow(&self) -> &std::path::Path { + self.as_ref() + } +} + +impl Borrow for std::path::PathBuf { + #[inline] + fn borrow(&self) -> &Path { + self.as_ref() + } +} + +impl FromStr for PathBuf { + type Err = Infallible; + + #[inline] + fn from_str(s: &str) -> Result { + Ok(s.into()) + } +} + +impl FromStr for RelativePathBuf { + type Err = TryRelativeError; + + #[inline] + fn from_str(s: &str) -> Result { + s.try_into() + } +} + +impl FromStr for AbsolutePathBuf { + type Err = TryAbsoluteError; + + #[inline] + fn from_str(s: &str) -> Result { + s.try_into() + } +} + +impl> Extend

for PathBuf { + fn extend>(&mut self, iter: T) { + for path in iter { + self.push(path); + } + } +} + +impl> FromIterator

for PathBuf { + fn from_iter>(iter: T) -> Self { + let mut buf = Self::new_unchecked(std::path::PathBuf::new()); + buf.extend(iter); + buf + } +} + +impl<'a, Form: PathForm> IntoIterator for &'a PathBuf { + type Item = &'a OsStr; + + type IntoIter = std::path::Iter<'a>; + + #[inline] + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +#[inline] +fn box_to_box_unchecked(path: Box>) -> Box> { + // Safety: `Path` and `Path` differ only by PhantomData tag. + let ptr = Box::into_raw(path) as *mut Path; + unsafe { Box::from_raw(ptr) } +} + +#[inline] +fn std_box_to_box(path: Box) -> Box> { + // Safety: `Path` is a repr(transparent) wrapper around `std::path::Path`. + let ptr = Box::into_raw(path) as *mut Path; + unsafe { Box::from_raw(ptr) } +} + +#[inline] +fn std_arc_to_arc(path: Arc) -> Arc> { + // Safety: `Path` is a repr(transparent) wrapper around `std::path::Path`. + let ptr = Arc::into_raw(path) as *mut Path; + unsafe { Arc::from_raw(ptr) } +} + +#[inline] +fn std_rc_to_rc(path: Rc) -> Rc> { + // Safety: `Path` is a repr(transparent) wrapper around `std::path::Path`. + let ptr = Rc::into_raw(path) as *mut Path; + unsafe { Rc::from_raw(ptr) } +} + +/* +================================================================================ + AsRef +================================================================================ +*/ + +// Here we match all `AsRef` implementations on `std::path::Path` and `std::path::PathBuf`, +// adding casting variations where possible. + +macro_rules! impl_as_ref { + ([$($from:ty),* $(,)?] => $to:ty |$self:ident| $cast:block) => { + $( + impl AsRef<$to> for $from { + #[inline] + fn as_ref(&$self) -> &$to $cast + } + )* + }; +} + +// === To and from crate types === + +impl, To: PathForm> AsRef> for Path { + #[inline] + fn as_ref(&self) -> &Path { + self.cast() + } +} + +impl, To: PathForm> AsRef> for PathBuf { + #[inline] + fn as_ref(&self) -> &Path { + self.cast() + } +} + +impl_as_ref!( + [ + Box, Box, Box, + Cow<'_, RelativePath>, Cow<'_, AbsolutePath>, Cow<'_, CanonicalPath>, + Rc, Rc, Rc, + Arc, Arc, Arc, + ] + => Path |self| { self.cast() } +); + +impl_as_ref!( + [Box, Cow<'_, CanonicalPath>, Rc, Arc] + => AbsolutePath |self| { self.cast() } +); + +// === To and from std::path types === + +impl AsRef for Path { + #[inline] + fn as_ref(&self) -> &std::path::Path { + self.as_std_path() + } +} + +impl AsRef for PathBuf { + #[inline] + fn as_ref(&self) -> &std::path::Path { + self.as_std_path() + } +} + +impl_as_ref!( + [std::path::Path, std::path::PathBuf, std::path::Component<'_>] + => Path |self| { Path::new(self) } +); + +impl_as_ref!( + [Box, Cow<'_, std::path::Path>, Rc, Arc] + => Path |self| { Path::new(self.as_os_str()) } +); + +// === To and from string types === + +impl AsRef for Path { + #[inline] + fn as_ref(&self) -> &OsStr { + self.as_os_str() + } +} + +impl AsRef for PathBuf { + #[inline] + fn as_ref(&self) -> &OsStr { + self.as_os_str() + } +} + +impl_as_ref!([OsStr, OsString, Cow<'_, OsStr>, str, String] => Path |self| { Path::new(self) }); + +/* +================================================================================ + From +================================================================================ +*/ + +// Here we match all `From` implementations on `std::path::Path` and `std::path::PathBuf`, +// adding casting variations where possible. + +macro_rules! impl_from { + ([$($from:ty),* $(,)?] => $to:ty |$value:ident| $convert:block) => { + $( + impl From<$from> for $to { + #[inline] + fn from($value: $from) -> Self $convert + } + )* + }; + (<$form:ident> $from:ty => $to:ty |$value:ident| $convert:block) => { + impl<$form: PathForm> From<$from> for $to { + #[inline] + fn from($value: $from) -> Self $convert + } + }; +} + +macro_rules! impl_into_std { + (<$form:ident> $from:ty => [$($to:ty),* $(,)?] |$value:ident| $convert:block) => { + $( + impl<$form: IsAbsolute> From<$from> for $to { + #[inline] + fn from($value: $from) -> Self $convert + } + )* + }; +} + +// ===== Owned to Owned ===== + +// === To and from crate types === + +impl_from!([RelativePathBuf, AbsolutePathBuf, CanonicalPathBuf] => PathBuf + |buf| { buf.cast_into() } +); +impl_from!([CanonicalPathBuf] => AbsolutePathBuf |buf| { buf.cast_into() }); + +#[inline] +fn box_to_box, To: PathForm>(path: Box>) -> Box> { + box_to_box_unchecked(path) +} +impl_from!([Box, Box, Box] => Box + |path| { box_to_box(path) } +); +impl_from!([Box] => Box |path| { box_to_box(path) }); + +impl_from!( PathBuf => Box> |buf| { buf.into_boxed_path() }); +impl_from!([RelativePathBuf, AbsolutePathBuf, CanonicalPathBuf] => Box + |buf| { buf.into_boxed_path().into() } +); +impl_from!([CanonicalPathBuf] => Box |buf| { buf.into_boxed_path().into() }); + +impl_from!( Box> => PathBuf |path| { path.into_path_buf() }); +impl_from!([Box, Box, Box] => PathBuf + |path| { path.into_path_buf().into() } +); +impl_from!([Box] => AbsolutePathBuf |path| { path.into_path_buf().into() }); + +impl_from!( PathBuf => Cow<'_, Path> |buf| { Self::Owned(buf) }); +impl_from!([RelativePathBuf, AbsolutePathBuf, CanonicalPathBuf] => Cow<'_, Path> + |buf| { Self::Owned(buf.into()) } +); +impl_from!([CanonicalPathBuf] => Cow<'_, AbsolutePath> |buf| { Self::Owned(buf.into()) }); + +impl_from!( Cow<'_, Path> => PathBuf |cow| { cow.into_owned() }); +impl_from!([Cow<'_, RelativePath>, Cow<'_, AbsolutePath>, Cow<'_, CanonicalPath>] => PathBuf + |cow| { cow.into_owned().into() } +); +impl_from!([Cow<'_, CanonicalPath>] => AbsolutePathBuf |cow| { cow.into_owned().into() }); + +#[inline] +fn cow_to_box(cow: Cow<'_, From>) -> Box +where + From: ?Sized + ToOwned, + for<'a> &'a From: Into>, + From::Owned: Into>, + To: ?Sized, +{ + match cow { + Cow::Borrowed(path) => path.into(), + Cow::Owned(path) => path.into(), + } +} +impl_from!( Cow<'_, Path> => Box> |cow| { cow_to_box(cow) }); +impl_from!([Cow<'_, RelativePath>, Cow<'_, AbsolutePath>, Cow<'_, CanonicalPath>] => Box + |cow| { cow_to_box(cow) } +); +impl_from!([Cow<'_, CanonicalPath>] => Box |cow| { cow_to_box(cow) }); + +#[inline] +fn buf_to_arc, To: PathForm>(buf: PathBuf) -> Arc> { + std_arc_to_arc(buf.inner.into()) +} +impl_from!( PathBuf => Arc> |buf| { buf_to_arc(buf) }); +impl_from!([RelativePathBuf, AbsolutePathBuf, CanonicalPathBuf] => Arc + |buf| { buf_to_arc(buf) } +); +impl_from!([CanonicalPathBuf] => Arc |buf| { buf_to_arc(buf) }); + +#[inline] +fn buf_to_rc, To: PathForm>(buf: PathBuf) -> Rc> { + std_rc_to_rc(buf.inner.into()) +} +impl_from!( PathBuf => Rc> |buf| { buf_to_rc(buf) }); +impl_from!([RelativePathBuf, AbsolutePathBuf, CanonicalPathBuf] => Rc + |buf| { buf_to_rc(buf) } +); +impl_from!([CanonicalPathBuf] => Rc |buf| { buf_to_rc(buf) }); + +// === To and from std::path types === + +impl_into_std!( PathBuf => [std::path::PathBuf] |buf| { buf.inner }); +impl_into_std!( + PathBuf => [ + Box, Cow<'_, std::path::Path>, Arc, Rc + ] + |buf| { buf.inner.into() } +); +impl_into_std!( Box> => [std::path::PathBuf, Box] + |path| { path.inner.into() } +); + +impl_from!([std::path::PathBuf] => PathBuf |buf| { Self::new_unchecked(buf) }); +impl_from!([Box] => PathBuf |path| { Self::new_unchecked(path.into()) }); +impl_from!([Cow<'_, std::path::Path>] => PathBuf |cow| { Self::new_unchecked(cow.into()) }); + +impl From> for Box { + #[inline] + fn from(path: Box) -> Self { + std_box_to_box(path) + } +} +impl_from!([std::path::PathBuf] => Box |buf| { buf.into_boxed_path().into() }); +impl_from!([Cow<'_, std::path::Path>] => Box |cow| { cow_to_box(cow) }); + +// === To and from string types === + +impl_from!( PathBuf => OsString |buf| { buf.inner.into() }); +impl_from!([OsString, String] => PathBuf |s| { Self::new_unchecked(s.into()) }); + +// ===== Borrowed to Owned ===== + +// === To and from crate types === +// Here we also add casting conversions from `T: impl AsRef>` to `PathBuf`. + +impl, To: PathForm> From<&Path> for Box> { + #[inline] + fn from(path: &Path) -> Self { + std_box_to_box(path.inner.into()) + } +} + +impl<'a, Source: PathCast, To: PathForm> From<&'a Path> for Cow<'a, Path> { + #[inline] + fn from(path: &'a Path) -> Self { + path.cast().into() + } +} + +impl<'a, Source: PathCast, To: PathForm> From<&'a PathBuf> for Cow<'a, Path> { + #[inline] + fn from(buf: &'a PathBuf) -> Self { + buf.cast().into() + } +} + +impl, To: PathForm> From<&Path> for Arc> { + #[inline] + fn from(path: &Path) -> Self { + std_arc_to_arc(path.inner.into()) + } +} + +impl, To: PathForm> From<&Path> for Rc> { + #[inline] + fn from(path: &Path) -> Self { + std_rc_to_rc(path.inner.into()) + } +} + +impl> From<&T> for RelativePathBuf { + #[inline] + fn from(s: &T) -> Self { + Self::new_unchecked(s.as_ref().into()) + } +} + +impl> From<&T> for AbsolutePathBuf { + #[inline] + fn from(s: &T) -> Self { + Self::new_unchecked(s.as_ref().into()) + } +} + +impl> From<&T> for CanonicalPathBuf { + #[inline] + fn from(s: &T) -> Self { + Self::new_unchecked(s.as_ref().into()) + } +} + +// === To and from std::path types === + +impl_into_std!( + &Path => [Box, Arc, Rc] + |path| { path.inner.into() } +); + +impl<'a, Form: IsAbsolute> From<&'a Path> for Cow<'a, std::path::Path> { + #[inline] + fn from(path: &'a Path) -> Self { + path.inner.into() + } +} + +impl<'a, Form: IsAbsolute> From<&'a PathBuf> for Cow<'a, std::path::Path> { + #[inline] + fn from(buf: &'a PathBuf) -> Self { + Self::Borrowed(buf.as_ref()) + } +} + +impl_from!([&std::path::Path] => Box |path| { Path::new(path).into() }); + +// === To and from string types === + +impl> From<&T> for PathBuf { + #[inline] + fn from(s: &T) -> Self { + Self::new_unchecked(s.as_ref().into()) + } +} + +/* +================================================================================ + TryFrom +================================================================================ +*/ + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct TryRelativeError; + +impl fmt::Display for TryRelativeError { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(fmt, "path was not a relative path") + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct TryAbsoluteError; + +impl fmt::Display for TryAbsoluteError { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(fmt, "path was not an absolute path") + } +} + +// ===== Borrowed to borrowed ===== +// Here we match all `AsRef` implementations on `std::path::Path`. + +macro_rules! impl_try_from_borrowed_to_borrowed { + ([$($from:ty),* $(,)?], |$value:ident| $convert:block $(,)?) => { + $( + impl<'a> TryFrom<&'a $from> for &'a RelativePath { + type Error = TryRelativeError; + + #[inline] + fn try_from($value: &'a $from) -> Result $convert + } + + impl<'a> TryFrom<&'a $from> for &'a AbsolutePath { + type Error = TryAbsoluteError; + + #[inline] + fn try_from($value: &'a $from) -> Result $convert + } + )* + }; +} + +// === From crate types === + +impl<'a> TryFrom<&'a Path> for &'a RelativePath { + type Error = TryRelativeError; + + #[inline] + fn try_from(path: &'a Path) -> Result { + path.try_relative().map_err(|_| TryRelativeError) + } +} + +impl<'a> TryFrom<&'a Path> for &'a AbsolutePath { + type Error = TryAbsoluteError; + + #[inline] + fn try_from(path: &'a Path) -> Result { + path.try_absolute().map_err(|_| TryAbsoluteError) + } +} + +impl_try_from_borrowed_to_borrowed!([PathBuf], |buf| { Path::new(buf).try_into() }); + +// === From std::path types === + +impl_try_from_borrowed_to_borrowed!([std::path::Path], |path| { Path::new(path).try_into() }); +impl_try_from_borrowed_to_borrowed!([std::path::PathBuf], |buf| { Path::new(buf).try_into() }); +impl_try_from_borrowed_to_borrowed!([std::path::Component<'_>], |component| { + Path::new(component).try_into() +}); +impl_try_from_borrowed_to_borrowed!([std::path::Components<'_>], |components| { + Path::new(components).try_into() +}); +impl_try_from_borrowed_to_borrowed!([std::path::Iter<'_>], |iter| { Path::new(iter).try_into() }); + +// === From string types === + +impl_try_from_borrowed_to_borrowed!( + [OsStr, OsString, Cow<'_, OsStr>, str, String], + |s| { Path::new(s).try_into() }, +); + +// ===== Borrowed to Owned ===== +// Here we match all `From<&T>` implementations on `std::path::Path` and `std::path::PathBuf`. +// Note that to match `From<&T: AsRef>` on `std::path::PathBuf`, +// we add string conversions and a few others. + +macro_rules! impl_try_from_borrowed_to_owned { + ([$($from:ty),* $(,)?] => $rel:ty, $abs:ty $(,)?) => { + $( + impl TryFrom<&$from> for $rel { + type Error = TryRelativeError; + + #[inline] + fn try_from(path: &$from) -> Result { + let path: &RelativePath = path.try_into()?; + Ok(path.into()) + } + } + + impl TryFrom<&$from> for $abs { + type Error = TryAbsoluteError; + + #[inline] + fn try_from(path: &$from) -> Result { + let path: &AbsolutePath = path.try_into()?; + Ok(path.into()) + } + } + )* + }; + (<$life:lifetime> $from:ty => $rel:ty, $abs:ty $(,)?) => { + impl<$life> TryFrom<&$life $from> for $rel { + type Error = TryRelativeError; + + #[inline] + fn try_from(path: &$life $from) -> Result { + let path: &RelativePath = path.try_into()?; + Ok(path.into()) + } + } + + impl<$life> TryFrom<&$life $from> for $abs { + type Error = TryAbsoluteError; + + #[inline] + fn try_from(path: &$life $from) -> Result { + let path: &AbsolutePath = path.try_into()?; + Ok(path.into()) + } + } + }; +} + +// === From crate types === + +impl_try_from_borrowed_to_owned!([Path] => Box, Box); +impl_try_from_borrowed_to_owned!(<'a> Path => Cow<'a, RelativePath>, Cow<'a, AbsolutePath>); +impl_try_from_borrowed_to_owned!([Path] => Arc, Arc); +impl_try_from_borrowed_to_owned!([Path] => Rc, Rc); + +impl_try_from_borrowed_to_owned!([Path, PathBuf] => RelativePathBuf, AbsolutePathBuf); +impl_try_from_borrowed_to_owned!(<'a> PathBuf => Cow<'a, RelativePath>, Cow<'a, AbsolutePath>); + +// === From std::path types === + +impl_try_from_borrowed_to_owned!([std::path::Path] => Box, Box); + +impl_try_from_borrowed_to_owned!( + [std::path::Path, std::path::PathBuf, std::path::Component<'_>] + => RelativePathBuf, AbsolutePathBuf +); + +// === From string types === + +impl_try_from_borrowed_to_owned!( + [OsStr, OsString, Cow<'_, OsStr>, str, String] => RelativePathBuf, AbsolutePathBuf +); + +// ===== Owned to Owned ===== +// Here we match all `From` implementations on `std::path::Path` and `std::path::PathBuf` +// where `T` is an owned type. + +// === From crate types === + +impl TryFrom for RelativePathBuf { + type Error = PathBuf; + + #[inline] + fn try_from(buf: PathBuf) -> Result { + buf.try_into_relative() + } +} + +impl TryFrom for AbsolutePathBuf { + type Error = PathBuf; + + #[inline] + fn try_from(buf: PathBuf) -> Result { + buf.try_into_absolute() + } +} + +impl TryFrom> for RelativePathBuf { + type Error = Box; + + #[inline] + fn try_from(path: Box) -> Result { + if path.is_relative() { + Ok(Self::new_unchecked(path.inner.into())) + } else { + Err(path) + } + } +} + +impl TryFrom> for AbsolutePathBuf { + type Error = Box; + + #[inline] + fn try_from(path: Box) -> Result { + if path.is_absolute() { + Ok(Self::new_unchecked(path.inner.into())) + } else { + Err(path) + } + } +} + +impl TryFrom> for Box { + type Error = Box; + + #[inline] + fn try_from(path: Box) -> Result { + if path.is_relative() { + Ok(box_to_box_unchecked(path)) + } else { + Err(path) + } + } +} + +impl TryFrom> for Box { + type Error = Box; + + #[inline] + fn try_from(path: Box) -> Result { + if path.is_absolute() { + Ok(box_to_box_unchecked(path)) + } else { + Err(path) + } + } +} + +impl TryFrom for Box { + type Error = PathBuf; + + #[inline] + fn try_from(buf: PathBuf) -> Result { + RelativePathBuf::try_from(buf).map(Into::into) + } +} + +impl TryFrom for Box { + type Error = PathBuf; + + #[inline] + fn try_from(buf: PathBuf) -> Result { + AbsolutePathBuf::try_from(buf).map(Into::into) + } +} + +impl<'a> TryFrom> for RelativePathBuf { + type Error = Cow<'a, Path>; + + #[inline] + fn try_from(path: Cow<'a, Path>) -> Result { + match path { + Cow::Borrowed(path) => Self::try_from(path).map_err(|_| Cow::Borrowed(path)), + Cow::Owned(path) => Self::try_from(path).map_err(Cow::Owned), + } + } +} + +impl<'a> TryFrom> for AbsolutePathBuf { + type Error = Cow<'a, Path>; + + #[inline] + fn try_from(path: Cow<'a, Path>) -> Result { + match path { + Cow::Borrowed(path) => Self::try_from(path).map_err(|_| Cow::Borrowed(path)), + Cow::Owned(path) => Self::try_from(path).map_err(Cow::Owned), + } + } +} + +impl<'a> TryFrom> for Box { + type Error = Cow<'a, Path>; + + #[inline] + fn try_from(path: Cow<'a, Path>) -> Result { + match path { + Cow::Borrowed(path) => Box::try_from(path).map_err(|_| Cow::Borrowed(path)), + Cow::Owned(path) => Box::try_from(path).map_err(Cow::Owned), + } + } +} + +impl<'a> TryFrom> for Box { + type Error = Cow<'a, Path>; + + #[inline] + fn try_from(path: Cow<'a, Path>) -> Result { + match path { + Cow::Borrowed(path) => Box::try_from(path).map_err(|_| Cow::Borrowed(path)), + Cow::Owned(path) => Box::try_from(path).map_err(Cow::Owned), + } + } +} + +// === From std::path types === + +impl TryFrom for RelativePathBuf { + type Error = std::path::PathBuf; + + #[inline] + fn try_from(buf: std::path::PathBuf) -> Result { + Self::try_from(PathBuf::from(buf)).map_err(|buf| buf.inner) + } +} + +impl TryFrom for AbsolutePathBuf { + type Error = std::path::PathBuf; + + #[inline] + fn try_from(buf: std::path::PathBuf) -> Result { + Self::try_from(PathBuf::from(buf)).map_err(|buf| buf.inner) + } +} + +impl TryFrom> for RelativePathBuf { + type Error = Box; + + #[inline] + fn try_from(path: Box) -> Result { + if path.is_relative() { + Ok(Self::new_unchecked(path.into())) + } else { + Err(path) + } + } +} + +impl TryFrom> for AbsolutePathBuf { + type Error = Box; + + #[inline] + fn try_from(path: Box) -> Result { + if path.is_absolute() { + Ok(Self::new_unchecked(path.into())) + } else { + Err(path) + } + } +} + +impl TryFrom> for Box { + type Error = Box; + + #[inline] + fn try_from(path: Box) -> Result { + if path.is_relative() { + Ok(std_box_to_box(path)) + } else { + Err(path) + } + } +} + +impl TryFrom> for Box { + type Error = Box; + + #[inline] + fn try_from(path: Box) -> Result { + if path.is_absolute() { + Ok(std_box_to_box(path)) + } else { + Err(path) + } + } +} + +impl TryFrom for Box { + type Error = std::path::PathBuf; + + #[inline] + fn try_from(buf: std::path::PathBuf) -> Result { + RelativePathBuf::try_from(buf).map(Into::into) + } +} + +impl TryFrom for Box { + type Error = std::path::PathBuf; + + #[inline] + fn try_from(buf: std::path::PathBuf) -> Result { + AbsolutePathBuf::try_from(buf).map(Into::into) + } +} + +impl<'a> TryFrom> for RelativePathBuf { + type Error = Cow<'a, std::path::Path>; + + #[inline] + fn try_from(path: Cow<'a, std::path::Path>) -> Result { + match path { + Cow::Borrowed(path) => Self::try_from(path).map_err(|_| Cow::Borrowed(path)), + Cow::Owned(path) => Self::try_from(path).map_err(Cow::Owned), + } + } +} + +impl<'a> TryFrom> for AbsolutePathBuf { + type Error = Cow<'a, std::path::Path>; + + #[inline] + fn try_from(path: Cow<'a, std::path::Path>) -> Result { + match path { + Cow::Borrowed(path) => Self::try_from(path).map_err(|_| Cow::Borrowed(path)), + Cow::Owned(path) => Self::try_from(path).map_err(Cow::Owned), + } + } +} + +impl<'a> TryFrom> for Box { + type Error = Cow<'a, std::path::Path>; + + #[inline] + fn try_from(path: Cow<'a, std::path::Path>) -> Result { + match path { + Cow::Borrowed(path) => Box::try_from(path).map_err(|_| Cow::Borrowed(path)), + Cow::Owned(path) => Box::try_from(path).map_err(Cow::Owned), + } + } +} + +impl<'a> TryFrom> for Box { + type Error = Cow<'a, std::path::Path>; + + #[inline] + fn try_from(path: Cow<'a, std::path::Path>) -> Result { + match path { + Cow::Borrowed(path) => Box::try_from(path).map_err(|_| Cow::Borrowed(path)), + Cow::Owned(path) => Box::try_from(path).map_err(Cow::Owned), + } + } +} + +// === From string types === + +impl TryFrom for RelativePathBuf { + type Error = OsString; + + #[inline] + fn try_from(s: OsString) -> Result { + Self::try_from(PathBuf::from(s)).map_err(|buf| buf.into_os_string()) + } +} + +impl TryFrom for AbsolutePathBuf { + type Error = OsString; + + #[inline] + fn try_from(s: OsString) -> Result { + Self::try_from(PathBuf::from(s)).map_err(|buf| buf.into_os_string()) + } +} + +impl TryFrom for RelativePathBuf { + type Error = String; + + #[inline] + fn try_from(s: String) -> Result { + if Path::new(&s).is_relative() { + Ok(Self::new_unchecked(s.into())) + } else { + Err(s) + } + } +} + +impl TryFrom for AbsolutePathBuf { + type Error = String; + + #[inline] + fn try_from(s: String) -> Result { + if Path::new(&s).is_absolute() { + Ok(Self::new_unchecked(s.into())) + } else { + Err(s) + } + } +} + +/* +================================================================================ + PartialEq, Eq, PartialOrd, and Ord +================================================================================ +*/ + +// Here we match all `PartialEq` and `PartialOrd` implementations on `std::path::Path` +// and `std::path::PathBuf`, adding casting variations where possible. + +// === Between crate types === + +impl PartialEq for Path { + fn eq(&self, other: &Self) -> bool { + self.inner == other.inner + } +} + +impl Eq for Path {} + +impl PartialOrd for Path { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.inner.cmp(&other.inner)) + } +} + +impl Ord for Path { + fn cmp(&self, other: &Self) -> Ordering { + self.inner.cmp(&other.inner) + } +} + +impl Hash for Path { + fn hash(&self, state: &mut H) { + self.inner.hash(state); + } +} + +impl PartialEq for PathBuf { + fn eq(&self, other: &Self) -> bool { + self.inner == other.inner + } +} + +impl Eq for PathBuf {} + +impl PartialOrd for PathBuf { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.inner.cmp(&other.inner)) + } +} + +impl Ord for PathBuf { + fn cmp(&self, other: &Self) -> Ordering { + self.inner.cmp(&other.inner) + } +} + +impl Hash for PathBuf { + fn hash(&self, state: &mut H) { + self.inner.hash(state); + } +} + +macro_rules! impl_cmp { + (<$($life:lifetime),*> $lhs:ty, $rhs:ty) => { + impl<$($life,)* Form: PathForm> PartialEq<$rhs> for $lhs { + #[inline] + fn eq(&self, other: &$rhs) -> bool { + as PartialEq>::eq(self, other) + } + } + + impl<$($life,)* Form: PathForm> PartialEq<$lhs> for $rhs { + #[inline] + fn eq(&self, other: &$lhs) -> bool { + as PartialEq>::eq(self, other) + } + } + + impl<$($life,)* Form: PathForm> PartialOrd<$rhs> for $lhs { + #[inline] + fn partial_cmp(&self, other: &$rhs) -> Option { + as PartialOrd>::partial_cmp(self, other) + } + } + + impl<$($life,)* Form: PathForm> PartialOrd<$lhs> for $rhs { + #[inline] + fn partial_cmp(&self, other: &$lhs) -> Option { + as PartialOrd>::partial_cmp(self, other) + } + } + }; +} + +impl_cmp!(<> PathBuf, Path); +impl_cmp!(<'a> PathBuf, &'a Path); +impl_cmp!(<'a> Cow<'a, Path>, Path); +impl_cmp!(<'a, 'b> Cow<'a, Path>, &'b Path); +impl_cmp!(<'a> Cow<'a, Path>, PathBuf); + +macro_rules! impl_cmp_cast { + (<$($life:lifetime),*> $lhs:ty, $rhs:ty) => { + impl<$($life),*> PartialEq<$rhs> for $lhs { + #[inline] + fn eq(&self, other: &$rhs) -> bool { + ::eq(self.cast(), other.cast()) + } + } + + impl<$($life),*> PartialEq<$lhs> for $rhs { + #[inline] + fn eq(&self, other: &$lhs) -> bool { + ::eq(self.cast(), other.cast()) + } + } + + impl<$($life),*> PartialOrd<$rhs> for $lhs { + #[inline] + fn partial_cmp(&self, other: &$rhs) -> Option { + ::partial_cmp(self.cast(), other.cast()) + } + } + + impl<$($life),*> PartialOrd<$lhs> for $rhs { + #[inline] + fn partial_cmp(&self, other: &$lhs) -> Option { + ::partial_cmp(self.cast(), other.cast()) + } + } + }; +} + +impl_cmp_cast!(<> Path, RelativePath); +impl_cmp_cast!(<> Path, AbsolutePath); +impl_cmp_cast!(<> Path, CanonicalPath); +impl_cmp_cast!(<> AbsolutePath, CanonicalPath); +impl_cmp_cast!(<> PathBuf, RelativePathBuf); +impl_cmp_cast!(<> PathBuf, AbsolutePathBuf); +impl_cmp_cast!(<> PathBuf, CanonicalPathBuf); +impl_cmp_cast!(<> AbsolutePathBuf, CanonicalPathBuf); + +impl_cmp_cast!(<'a> &'a Path, RelativePath); +impl_cmp_cast!(<'a> &'a Path, AbsolutePath); +impl_cmp_cast!(<'a> &'a Path, CanonicalPath); +impl_cmp_cast!(<'a> &'a AbsolutePath, CanonicalPath); +impl_cmp_cast!(<'a> Path, &'a RelativePath); +impl_cmp_cast!(<'a> Path, &'a AbsolutePath); +impl_cmp_cast!(<'a> Path, &'a CanonicalPath); +impl_cmp_cast!(<'a> AbsolutePath, &'a CanonicalPath); + +impl_cmp_cast!(<> PathBuf, RelativePath); +impl_cmp_cast!(<> PathBuf, AbsolutePath); +impl_cmp_cast!(<> PathBuf, CanonicalPath); +impl_cmp_cast!(<> AbsolutePathBuf, CanonicalPath); +impl_cmp_cast!(<> RelativePathBuf, Path); +impl_cmp_cast!(<> AbsolutePathBuf, Path); +impl_cmp_cast!(<> CanonicalPathBuf, Path); +impl_cmp_cast!(<> CanonicalPathBuf, AbsolutePath); + +impl_cmp_cast!(<'a> PathBuf, &'a RelativePath); +impl_cmp_cast!(<'a> PathBuf, &'a AbsolutePath); +impl_cmp_cast!(<'a> PathBuf, &'a CanonicalPath); +impl_cmp_cast!(<'a> AbsolutePathBuf, &'a CanonicalPath); +impl_cmp_cast!(<'a> RelativePathBuf, &'a Path); +impl_cmp_cast!(<'a> AbsolutePathBuf, &'a Path); +impl_cmp_cast!(<'a> CanonicalPathBuf, &'a Path); +impl_cmp_cast!(<'a> CanonicalPathBuf, &'a AbsolutePath); + +impl_cmp_cast!(<'a> Cow<'a, Path>, RelativePath); +impl_cmp_cast!(<'a> Cow<'a, Path>, AbsolutePath); +impl_cmp_cast!(<'a> Cow<'a, Path>, CanonicalPath); +impl_cmp_cast!(<'a> Cow<'a, AbsolutePath>, CanonicalPath); +impl_cmp_cast!(<'a> Cow<'a, RelativePath>, Path); +impl_cmp_cast!(<'a> Cow<'a, AbsolutePath>, Path); +impl_cmp_cast!(<'a> Cow<'a, CanonicalPath>, Path); +impl_cmp_cast!(<'a> Cow<'a, CanonicalPath>, AbsolutePath); + +impl_cmp_cast!(<'a, 'b> Cow<'a, Path>, &'b RelativePath); +impl_cmp_cast!(<'a, 'b> Cow<'a, Path>, &'b AbsolutePath); +impl_cmp_cast!(<'a, 'b> Cow<'a, Path>, &'b CanonicalPath); +impl_cmp_cast!(<'a, 'b> Cow<'a, AbsolutePath>, &'b CanonicalPath); +impl_cmp_cast!(<'a, 'b> Cow<'a, RelativePath>, &'b Path); +impl_cmp_cast!(<'a, 'b> Cow<'a, AbsolutePath>, &'b Path); +impl_cmp_cast!(<'a, 'b> Cow<'a, CanonicalPath>, &'b Path); +impl_cmp_cast!(<'a, 'b> Cow<'a, CanonicalPath>, &'b AbsolutePath); + +impl_cmp_cast!(<'a> Cow<'a, Path>, RelativePathBuf); +impl_cmp_cast!(<'a> Cow<'a, Path>, AbsolutePathBuf); +impl_cmp_cast!(<'a> Cow<'a, Path>, CanonicalPathBuf); +impl_cmp_cast!(<'a> Cow<'a, AbsolutePath>, CanonicalPathBuf); +impl_cmp_cast!(<'a> Cow<'a, RelativePath>, PathBuf); +impl_cmp_cast!(<'a> Cow<'a, AbsolutePath>, PathBuf); +impl_cmp_cast!(<'a> Cow<'a, CanonicalPath>, PathBuf); +impl_cmp_cast!(<'a> Cow<'a, CanonicalPath>, AbsolutePathBuf); + +// === Between std::path types === + +macro_rules! impl_cmp_std { + (<$($life:lifetime),*> $lhs:ty, $rhs:ty) => { + impl<$($life,)* Form: PathForm> PartialEq<$rhs> for $lhs { + #[inline] + fn eq(&self, other: &$rhs) -> bool { + ::eq(self.as_ref(), other.as_any()) + } + } + + impl<$($life,)* Form: PathForm> PartialEq<$lhs> for $rhs { + #[inline] + fn eq(&self, other: &$lhs) -> bool { + ::eq(self.as_any(), other.as_ref()) + } + } + + impl<$($life,)* Form: PathForm> PartialOrd<$rhs> for $lhs { + #[inline] + fn partial_cmp(&self, other: &$rhs) -> Option { + ::partial_cmp(self.as_ref(), other.as_any()) + } + } + + impl<$($life,)* Form: PathForm> PartialOrd<$lhs> for $rhs { + #[inline] + fn partial_cmp(&self, other: &$lhs) -> Option { + ::partial_cmp(self.as_any(), other.as_ref()) + } + } + }; +} + +impl_cmp_std!(<> std::path::Path, Path); +impl_cmp_std!(<> std::path::PathBuf, Path); +impl_cmp_std!(<'a> std::path::PathBuf, &'a Path); +impl_cmp_std!(<'a> Cow<'a, std::path::Path>, Path); +impl_cmp_std!(<'a, 'b> Cow<'a, std::path::Path>, &'b Path); + +impl_cmp_std!(<> std::path::Path, PathBuf); +impl_cmp_std!(<'a> &'a std::path::Path, PathBuf); +impl_cmp_std!(<> std::path::PathBuf, PathBuf); +impl_cmp_std!(<'a> Cow<'a, std::path::Path>, PathBuf); + +// === Between string types === + +impl_cmp_std!(<> OsStr, Path); +impl_cmp_std!(<'a> OsStr, &'a Path); +impl_cmp_std!(<'a> &'a OsStr, Path); +impl_cmp_std!(<'a> Cow<'a, OsStr>, Path); +impl_cmp_std!(<'a, 'b> Cow<'b, OsStr>, &'a Path); +impl_cmp_std!(<> OsString, Path); +impl_cmp_std!(<'a> OsString, &'a Path); + +impl_cmp_std!(<> OsStr, PathBuf); +impl_cmp_std!(<'a> &'a OsStr, PathBuf); +impl_cmp_std!(<'a> Cow<'a, OsStr>, PathBuf); +impl_cmp_std!(<> OsString, PathBuf); diff --git a/typos.toml b/typos.toml index 92fecd5cb6..971aef7c15 100644 --- a/typos.toml +++ b/typos.toml @@ -17,6 +17,7 @@ extend-ignore-re = [ "--find ba\\b", "0x\\[ba be\\]", "\\)BaR'", + "fo�.txt", ] [type.rust.extend-words] From c5a00ca3f1d7457ce607648ebd216197acd992b2 Mon Sep 17 00:00:00 2001 From: Jack Wright <56345+ayax79@users.noreply.github.com> Date: Tue, 25 Jun 2024 19:14:15 -0700 Subject: [PATCH 06/16] update lock via cargo check to fix ci (#13233) --- Cargo.lock | 74 +++++++++++++++++++++++++++--------------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9b8f5273c8..9bb1992e02 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2769,7 +2769,7 @@ dependencies = [ [[package]] name = "nu" -version = "0.95.0" +version = "0.95.1" dependencies = [ "assert_cmd", "crossterm", @@ -2822,7 +2822,7 @@ dependencies = [ [[package]] name = "nu-cli" -version = "0.95.0" +version = "0.95.1" dependencies = [ "chrono", "crossterm", @@ -2857,7 +2857,7 @@ dependencies = [ [[package]] name = "nu-cmd-base" -version = "0.95.0" +version = "0.95.1" dependencies = [ "indexmap", "miette", @@ -2869,7 +2869,7 @@ dependencies = [ [[package]] name = "nu-cmd-extra" -version = "0.95.0" +version = "0.95.1" dependencies = [ "fancy-regex", "heck 0.5.0", @@ -2894,7 +2894,7 @@ dependencies = [ [[package]] name = "nu-cmd-lang" -version = "0.95.0" +version = "0.95.1" dependencies = [ "itertools 0.12.1", "nu-engine", @@ -2906,7 +2906,7 @@ dependencies = [ [[package]] name = "nu-cmd-plugin" -version = "0.95.0" +version = "0.95.1" dependencies = [ "itertools 0.12.1", "nu-engine", @@ -2917,7 +2917,7 @@ dependencies = [ [[package]] name = "nu-color-config" -version = "0.95.0" +version = "0.95.1" dependencies = [ "nu-ansi-term", "nu-engine", @@ -2929,7 +2929,7 @@ dependencies = [ [[package]] name = "nu-command" -version = "0.95.0" +version = "0.95.1" dependencies = [ "alphanumeric-sort", "base64 0.22.1", @@ -3038,7 +3038,7 @@ dependencies = [ [[package]] name = "nu-derive-value" -version = "0.95.0" +version = "0.95.1" dependencies = [ "convert_case", "proc-macro-error", @@ -3049,7 +3049,7 @@ dependencies = [ [[package]] name = "nu-engine" -version = "0.95.0" +version = "0.95.1" dependencies = [ "nu-glob", "nu-path", @@ -3059,7 +3059,7 @@ dependencies = [ [[package]] name = "nu-explore" -version = "0.95.0" +version = "0.95.1" dependencies = [ "ansi-str", "anyhow", @@ -3084,14 +3084,14 @@ dependencies = [ [[package]] name = "nu-glob" -version = "0.95.0" +version = "0.95.1" dependencies = [ "doc-comment", ] [[package]] name = "nu-json" -version = "0.95.0" +version = "0.95.1" dependencies = [ "linked-hash-map", "num-traits", @@ -3101,7 +3101,7 @@ dependencies = [ [[package]] name = "nu-lsp" -version = "0.95.0" +version = "0.95.1" dependencies = [ "assert-json-diff", "crossbeam-channel", @@ -3122,7 +3122,7 @@ dependencies = [ [[package]] name = "nu-parser" -version = "0.95.0" +version = "0.95.1" dependencies = [ "bytesize", "chrono", @@ -3138,7 +3138,7 @@ dependencies = [ [[package]] name = "nu-path" -version = "0.95.0" +version = "0.95.1" dependencies = [ "dirs-next", "omnipath", @@ -3147,7 +3147,7 @@ dependencies = [ [[package]] name = "nu-plugin" -version = "0.95.0" +version = "0.95.1" dependencies = [ "log", "nix", @@ -3162,7 +3162,7 @@ dependencies = [ [[package]] name = "nu-plugin-core" -version = "0.95.0" +version = "0.95.1" dependencies = [ "interprocess", "log", @@ -3176,7 +3176,7 @@ dependencies = [ [[package]] name = "nu-plugin-engine" -version = "0.95.0" +version = "0.95.1" dependencies = [ "log", "nu-engine", @@ -3191,7 +3191,7 @@ dependencies = [ [[package]] name = "nu-plugin-protocol" -version = "0.95.0" +version = "0.95.1" dependencies = [ "bincode", "nu-protocol", @@ -3203,7 +3203,7 @@ dependencies = [ [[package]] name = "nu-plugin-test-support" -version = "0.95.0" +version = "0.95.1" dependencies = [ "nu-ansi-term", "nu-cmd-lang", @@ -3221,7 +3221,7 @@ dependencies = [ [[package]] name = "nu-pretty-hex" -version = "0.95.0" +version = "0.95.1" dependencies = [ "heapless", "nu-ansi-term", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "nu-protocol" -version = "0.95.0" +version = "0.95.1" dependencies = [ "brotli", "byte-unit", @@ -3263,7 +3263,7 @@ dependencies = [ [[package]] name = "nu-std" -version = "0.95.0" +version = "0.95.1" dependencies = [ "log", "miette", @@ -3274,7 +3274,7 @@ dependencies = [ [[package]] name = "nu-system" -version = "0.95.0" +version = "0.95.1" dependencies = [ "chrono", "itertools 0.12.1", @@ -3292,7 +3292,7 @@ dependencies = [ [[package]] name = "nu-table" -version = "0.95.0" +version = "0.95.1" dependencies = [ "fancy-regex", "nu-ansi-term", @@ -3306,7 +3306,7 @@ dependencies = [ [[package]] name = "nu-term-grid" -version = "0.95.0" +version = "0.95.1" dependencies = [ "nu-utils", "unicode-width", @@ -3314,7 +3314,7 @@ dependencies = [ [[package]] name = "nu-test-support" -version = "0.95.0" +version = "0.95.1" dependencies = [ "nu-glob", "nu-path", @@ -3326,7 +3326,7 @@ dependencies = [ [[package]] name = "nu-utils" -version = "0.95.0" +version = "0.95.1" dependencies = [ "crossterm_winapi", "log", @@ -3352,7 +3352,7 @@ dependencies = [ [[package]] name = "nu_plugin_example" -version = "0.95.0" +version = "0.95.1" dependencies = [ "nu-cmd-lang", "nu-plugin", @@ -3362,7 +3362,7 @@ dependencies = [ [[package]] name = "nu_plugin_formats" -version = "0.95.0" +version = "0.95.1" dependencies = [ "eml-parser", "ical", @@ -3375,7 +3375,7 @@ dependencies = [ [[package]] name = "nu_plugin_gstat" -version = "0.95.0" +version = "0.95.1" dependencies = [ "git2", "nu-plugin", @@ -3384,7 +3384,7 @@ dependencies = [ [[package]] name = "nu_plugin_inc" -version = "0.95.0" +version = "0.95.1" dependencies = [ "nu-plugin", "nu-protocol", @@ -3393,7 +3393,7 @@ dependencies = [ [[package]] name = "nu_plugin_polars" -version = "0.95.0" +version = "0.95.1" dependencies = [ "chrono", "chrono-tz 0.9.0", @@ -3424,7 +3424,7 @@ dependencies = [ [[package]] name = "nu_plugin_query" -version = "0.95.0" +version = "0.95.1" dependencies = [ "gjson", "nu-plugin", @@ -3436,7 +3436,7 @@ dependencies = [ [[package]] name = "nu_plugin_stress_internals" -version = "0.95.0" +version = "0.95.1" dependencies = [ "interprocess", "serde", @@ -3562,7 +3562,7 @@ checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" [[package]] name = "nuon" -version = "0.95.0" +version = "0.95.1" dependencies = [ "chrono", "fancy-regex", From 38ecb6d3805cbfc7750367435ceeb4c19526f4d4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 26 Jun 2024 06:43:46 +0000 Subject: [PATCH 07/16] Bump uuid from 1.8.0 to 1.9.1 (#13227) --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- crates/nu_plugin_polars/Cargo.toml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9bb1992e02..a6d3457335 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6493,9 +6493,9 @@ checksum = "425a23c7b7145bc7620c9c445817c37b1f78b6790aee9f208133f3c028975b60" [[package]] name = "uuid" -version = "1.8.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0" +checksum = "5de17fd2f7da591098415cff336e12965a28061ddace43b59cb3c430179c9439" dependencies = [ "getrandom", "serde", diff --git a/Cargo.toml b/Cargo.toml index 3e02e7e066..c88eee88ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -172,7 +172,7 @@ uu_mv = "0.0.26" uu_whoami = "0.0.26" uu_uname = "0.0.26" uucore = "0.0.26" -uuid = "1.8.0" +uuid = "1.9.1" v_htmlescape = "0.15.0" wax = "0.6" which = "6.0.0" diff --git a/crates/nu_plugin_polars/Cargo.toml b/crates/nu_plugin_polars/Cargo.toml index 77bb84e988..09906732b7 100644 --- a/crates/nu_plugin_polars/Cargo.toml +++ b/crates/nu_plugin_polars/Cargo.toml @@ -36,7 +36,7 @@ polars-ops = { version = "0.40"} polars-plan = { version = "0.40", features = ["regex"]} polars-utils = { version = "0.40"} typetag = "0.2" -uuid = { version = "1.7", features = ["v4", "serde"] } +uuid = { version = "1.9", features = ["v4", "serde"] } [dependencies.polars] features = [ From 0fd0e36be87e51f298195791b2627a0fcf5a81ba Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 26 Jun 2024 14:44:31 +0800 Subject: [PATCH 08/16] Bump softprops/action-gh-release from 2.0.5 to 2.0.6 (#13230) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 2.0.5 to 2.0.6.

Release notes

Sourced from softprops/action-gh-release's releases.

v2.0.6

maintenance release with updated dependencies

Changelog

Sourced from softprops/action-gh-release's changelog.

2.0.6

  • maintenance release with updated dependencies
Commits
  • a74c6b7 update changelog
  • b909f76 update dist/index.js
  • e49d08f chore(deps): bump glob from 8.0.3 to 10.4.2
  • f12ad25 chore(deps): bump @​octokit/plugin-throttling from 4.3.2 to 9.3.0
  • 7039a82 chore: release 2.0.6
  • f9c2b6c chore: update deps and run build
  • 73738a6 chore(deps): bump node dep and @types/node
  • a500a35 Bump ts-jest from 29.0.3 to 29.1.4 (#459)
  • See full diff in compare view

Most Recent Ignore Conditions Applied to This Pull Request | Dependency Name | Ignore Conditions | | --- | --- | | softprops/action-gh-release | [< 0.2, > 0.1.13] |
[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=softprops/action-gh-release&package-manager=github_actions&previous-version=2.0.5&new-version=2.0.6)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/nightly-build.yml | 2 +- .github/workflows/release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/nightly-build.yml b/.github/workflows/nightly-build.yml index 9a30cae614..31533cc3d8 100644 --- a/.github/workflows/nightly-build.yml +++ b/.github/workflows/nightly-build.yml @@ -161,7 +161,7 @@ jobs: # REF: https://github.com/marketplace/actions/gh-release # Create a release only in nushell/nightly repo - name: Publish Archive - uses: softprops/action-gh-release@v2.0.5 + uses: softprops/action-gh-release@v2.0.6 if: ${{ startsWith(github.repository, 'nushell/nightly') }} with: prerelease: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 31fb1197a3..208acd42b5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -91,7 +91,7 @@ jobs: # REF: https://github.com/marketplace/actions/gh-release - name: Publish Archive - uses: softprops/action-gh-release@v2.0.5 + uses: softprops/action-gh-release@v2.0.6 if: ${{ startsWith(github.ref, 'refs/tags/') }} with: draft: true From b679c2bfa255e6153c5d962cbd541d7a63ba3cab Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 26 Jun 2024 14:44:50 +0800 Subject: [PATCH 09/16] Bump crate-ci/typos from 1.22.7 to 1.22.9 (#13229) Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.22.7 to 1.22.9.
Release notes

Sourced from crate-ci/typos's releases.

v1.22.9

[1.22.9] - 2024-06-22

Fixes

  • Stop correcting reoccurrence

v1.22.8

[1.22.8] - 2024-06-21

Features

  • (action) Add Arm, Mac support
Changelog

Sourced from crate-ci/typos's changelog.

[1.22.9] - 2024-06-22

Fixes

  • Stop correcting reoccurrence

[1.22.8] - 2024-06-21

Features

  • (action) Add Arm, Mac support
Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=crate-ci/typos&package-manager=github_actions&previous-version=1.22.7&new-version=1.22.9)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/typos.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/typos.yml b/.github/workflows/typos.yml index 33e7ac0945..95fc51b970 100644 --- a/.github/workflows/typos.yml +++ b/.github/workflows/typos.yml @@ -10,4 +10,4 @@ jobs: uses: actions/checkout@v4.1.7 - name: Check spelling - uses: crate-ci/typos@v1.22.7 + uses: crate-ci/typos@v1.22.9 From 8a7a407627d3c1f82f1cbde7fccfef278eae4a04 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 26 Jun 2024 22:48:11 +0000 Subject: [PATCH 10/16] Bump ratatui from 0.26.2 to 0.26.3 (#13228) --- Cargo.lock | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a6d3457335..f5c20e482d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -377,7 +377,7 @@ dependencies = [ "bitflags 2.5.0", "cexpr", "clang-sys", - "itertools 0.12.1", + "itertools 0.11.0", "lazy_static", "lazycell", "proc-macro2", @@ -1995,12 +1995,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "indoc" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5" - [[package]] name = "inotify" version = "0.9.6" @@ -4752,21 +4746,21 @@ dependencies = [ [[package]] name = "ratatui" -version = "0.26.2" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a564a852040e82671dc50a37d88f3aa83bbc690dfc6844cfe7a2591620206a80" +checksum = "f44c9e68fd46eda15c646fbb85e1040b657a58cdc8c98db1d97a55930d991eef" dependencies = [ "bitflags 2.5.0", "cassowary", "compact_str", "crossterm", - "indoc", "itertools 0.12.1", "lru", "paste", "stability", "strum", "unicode-segmentation", + "unicode-truncate", "unicode-width", ] @@ -6314,6 +6308,16 @@ version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" +[[package]] +name = "unicode-truncate" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a5fbabedabe362c618c714dbefda9927b5afc8e2a8102f47f081089a9019226" +dependencies = [ + "itertools 0.12.1", + "unicode-width", +] + [[package]] name = "unicode-width" version = "0.1.12" From 020f4436d95a62003ec10e0ba65d446840b6046a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 26 Jun 2024 22:48:45 +0000 Subject: [PATCH 11/16] Bump shadow-rs from 0.28.0 to 0.29.0 (#13226) --- Cargo.lock | 4 ++-- crates/nu-cmd-lang/Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f5c20e482d..cd7fe99800 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5435,9 +5435,9 @@ dependencies = [ [[package]] name = "shadow-rs" -version = "0.28.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d75516bdaee8f640543ad1f6e292448c23ce57143f812c3736ab4b0874383df" +checksum = "0a600f795d0894cda22235b44eea4b85c2a35b405f65523645ac8e35b306817a" dependencies = [ "const_format", "is_debug", diff --git a/crates/nu-cmd-lang/Cargo.toml b/crates/nu-cmd-lang/Cargo.toml index 262248e6d9..16ac1b893a 100644 --- a/crates/nu-cmd-lang/Cargo.toml +++ b/crates/nu-cmd-lang/Cargo.toml @@ -18,10 +18,10 @@ nu-protocol = { path = "../nu-protocol", version = "0.95.1" } nu-utils = { path = "../nu-utils", version = "0.95.1" } itertools = { workspace = true } -shadow-rs = { version = "0.28", default-features = false } +shadow-rs = { version = "0.29", default-features = false } [build-dependencies] -shadow-rs = { version = "0.28", default-features = false } +shadow-rs = { version = "0.29", default-features = false } [features] mimalloc = [] From 58e8ea6084831cdc3247b848a0004a41c1312375 Mon Sep 17 00:00:00 2001 From: NotTheDr01ds <32344964+NotTheDr01ds@users.noreply.github.com> Date: Wed, 26 Jun 2024 18:49:52 -0400 Subject: [PATCH 12/16] Update and add ls examples (#13222) # Description Based on #13219, added several examples to `ls` doc to demonstrate recursive directory listings. List of changes in this PR: * Add example for `ls **/*` to demonstrate recursive listing using glob pattern * Add example for `ls ...(glob )`... to demonstrate recursive listing using glob command * Remove `-s` from an example where it had no use (since it was based on the current directory and was not recursive) * Update the description of `ls -a ~ `... to clarify that it lists the full path of directories * Update the description of `ls -as ~ `... (the difference being the `-s`) to clarify that it lists only the filenames, not paths. # User-Facing Changes Help only # Tests + Formatting - :green_circle: `toolkit fmt` - :green_circle: `toolkit clippy` - :green_circle: `toolkit test` - :green_circle: `toolkit test stdlib` # After Submitting N/A --- crates/nu-command/src/filesystem/ls.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/nu-command/src/filesystem/ls.rs b/crates/nu-command/src/filesystem/ls.rs index a89cf04ed6..7eee57cfb6 100644 --- a/crates/nu-command/src/filesystem/ls.rs +++ b/crates/nu-command/src/filesystem/ls.rs @@ -175,20 +175,32 @@ impl Command for Ls { }, Example { description: "List files and directories whose name do not contain 'bar'", - example: "ls -s | where name !~ bar", + example: "ls | where name !~ bar", result: None, }, Example { - description: "List all dirs in your home directory", + description: "List the full path of all dirs in your home directory", example: "ls -a ~ | where type == dir", result: None, }, Example { description: - "List all dirs in your home directory which have not been modified in 7 days", + "List only the names (not paths) of all dirs in your home directory which have not been modified in 7 days", example: "ls -as ~ | where type == dir and modified < ((date now) - 7day)", result: None, }, + Example { + description: + "Recursively list all files and subdirectories under the current directory using a glob pattern", + example: "ls -a **/*", + result: None, + }, + Example { + description: + "Recursively list *.rs and *.toml files using the glob command", + example: "ls ...(glob **/*.{rs,toml})", + result: None, + }, Example { description: "List given paths and show directories themselves", example: "['/path/to/directory' '/path/to/file'] | each {|| ls -D $in } | flatten", From 198aedb6c2bee1a9ba43b3823381d37f5e5bd607 Mon Sep 17 00:00:00 2001 From: Piepmatz Date: Thu, 27 Jun 2024 00:50:14 +0200 Subject: [PATCH 13/16] Use `IntoValue` and `FromValue` derive macros in `nu_plugin_example` for example usage (#13220) # Description The derive macros provided by #13031 are very useful for plugin authors. In this PR I made use of these macros for two commands. # User-Facing Changes # Tests + Formatting - :green_circle: `toolkit fmt` - :green_circle: `toolkit clippy` - :green_circle: `toolkit test` - :green_circle: `toolkit test stdlib` # After Submitting This Example usage could be highlighted in the changelog for plugin authors as this is probably very useful for them. --- .../nu_plugin_example/src/commands/config.rs | 35 +++++++++++++++++-- crates/nu_plugin_example/src/commands/two.rs | 22 ++++++++---- tests/plugins/config.rs | 35 +++++-------------- 3 files changed, 56 insertions(+), 36 deletions(-) diff --git a/crates/nu_plugin_example/src/commands/config.rs b/crates/nu_plugin_example/src/commands/config.rs index f549bd324f..7716e27537 100644 --- a/crates/nu_plugin_example/src/commands/config.rs +++ b/crates/nu_plugin_example/src/commands/config.rs @@ -1,10 +1,37 @@ +use std::path::PathBuf; + use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; -use nu_protocol::{Category, LabeledError, Signature, Type, Value}; +use nu_protocol::{Category, FromValue, LabeledError, Signature, Spanned, Type, Value}; use crate::ExamplePlugin; pub struct Config; +/// Example config struct. +/// +/// Using the `FromValue` derive macro, structs can be easily loaded from [`Value`]s, +/// similar to serde's `Deserialize` macro. +/// This is handy for plugin configs or piped data. +/// All fields must implement [`FromValue`]. +/// For [`Option`] fields, they can be omitted in the config. +/// +/// This example shows that nested and spanned data work too, so you can describe nested +/// structures and get spans of values wrapped in [`Spanned`]. +/// Since this config uses only `Option`s, no field is required in the config. +#[allow(dead_code)] +#[derive(Debug, FromValue)] +struct PluginConfig { + path: Option>, + nested: Option, +} + +#[allow(dead_code)] +#[derive(Debug, FromValue)] +struct SubConfig { + bool: bool, + string: String, +} + impl SimplePluginCommand for Config { type Plugin = ExamplePlugin; @@ -39,7 +66,11 @@ impl SimplePluginCommand for Config { ) -> Result { let config = engine.get_plugin_config()?; match config { - Some(config) => Ok(config.clone()), + Some(value) => { + let config = PluginConfig::from_value(value.clone())?; + println!("got config {config:?}"); + Ok(value) + } None => Err(LabeledError::new("No config sent").with_label( "configuration for this plugin was not found in `$env.config.plugins.example`", call.head, diff --git a/crates/nu_plugin_example/src/commands/two.rs b/crates/nu_plugin_example/src/commands/two.rs index fcf2bf75ff..e02465e8b7 100644 --- a/crates/nu_plugin_example/src/commands/two.rs +++ b/crates/nu_plugin_example/src/commands/two.rs @@ -1,5 +1,5 @@ use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; -use nu_protocol::{record, Category, LabeledError, Signature, SyntaxShape, Value}; +use nu_protocol::{Category, IntoValue, LabeledError, Signature, SyntaxShape, Value}; use crate::ExamplePlugin; @@ -38,14 +38,22 @@ impl SimplePluginCommand for Two { ) -> Result { plugin.print_values(2, call, input)?; + // Use the IntoValue derive macro and trait to easily design output data. + #[derive(IntoValue)] + struct Output { + one: i64, + two: i64, + three: i64, + } + let vals = (0..10i64) .map(|i| { - let record = record! { - "one" => Value::int(i, call.head), - "two" => Value::int(2 * i, call.head), - "three" => Value::int(3 * i, call.head), - }; - Value::record(record, call.head) + Output { + one: i, + two: 2 * i, + three: 3 * i, + } + .into_value(call.head) }) .collect(); diff --git a/tests/plugins/config.rs b/tests/plugins/config.rs index 44f2797ceb..b110d2a7fd 100644 --- a/tests/plugins/config.rs +++ b/tests/plugins/config.rs @@ -1,27 +1,5 @@ use nu_test_support::nu_with_plugins; -#[test] -fn closure() { - let actual = nu_with_plugins!( - cwd: "tests", - plugin: ("nu_plugin_example"), - r#" - $env.env_value = "value from env" - - $env.config = { - plugins: { - example: {|| - $env.env_value - } - } - } - example config - "# - ); - - assert!(actual.out.contains("value from env")); -} - #[test] fn none() { let actual = nu_with_plugins!( @@ -34,7 +12,7 @@ fn none() { } #[test] -fn record() { +fn some() { let actual = nu_with_plugins!( cwd: "tests", plugin: ("nu_plugin_example"), @@ -42,8 +20,11 @@ fn record() { $env.config = { plugins: { example: { - key1: "value" - key2: "other" + path: "some/path", + nested: { + bool: true, + string: "Hello Example!" + } } } } @@ -51,6 +32,6 @@ fn record() { "# ); - assert!(actual.out.contains("value")); - assert!(actual.out.contains("other")); + assert!(actual.out.contains("some/path")); + assert!(actual.out.contains("Hello Example!")); } From ee74ec742385e0e6608edf3516f6a0cb97ef863e Mon Sep 17 00:00:00 2001 From: goldfish <37319612+ito-hiroki@users.noreply.github.com> Date: Thu, 27 Jun 2024 07:51:47 +0900 Subject: [PATCH 14/16] Make the subcommands (`from {csv, tsv, ssv}`) 0-based for consistency (#13209) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description fixed #11678 The sub-commands of from command (`from {csv, tsv, ssv}`) name columns starting from index 0. This behaviour is inconsistent with other commands such as `detect columns`. This PR makes the subcommands index 0-based. # User-Facing Changes The subcommands (`from {csv, tsv, ssv}`) return a table with the columns starting at index 0 if no header data is passed. ``` ~/Development/nushell> "foo bar baz" | from ssv -n -m 1 ╭───┬─────────┬─────────┬─────────╮ │ # │ column0 │ column1 │ column2 │ ├───┼─────────┼─────────┼─────────┤ │ 0 │ foo │ bar │ baz │ ╰───┴─────────┴─────────┴─────────╯ ~/Development/nushell> "foo,bar,baz" | from csv -n ╭───┬─────────┬─────────┬─────────╮ │ # │ column0 │ column1 │ column2 │ ├───┼─────────┼─────────┼─────────┤ │ 0 │ foo │ bar │ baz │ ╰───┴─────────┴─────────┴─────────╯ ~/Development/nushell> "foo\tbar\tbaz" | from tsv -n ╭───┬─────────┬─────────┬─────────╮ │ # │ column0 │ column1 │ column2 │ ├───┼─────────┼─────────┼─────────┤ │ 0 │ foo │ bar │ baz │ ╰───┴─────────┴─────────┴─────────╯ ``` # Tests + Formatting When I ran tests, `commands::touch::change_file_mtime_to_reference` failed with the following error. The error also occurs in the master branch, so it's probably unrelated to these changes. (maybe a problem with my dev environment) ``` $ toolkit check pr ~~~~~~~~ failures: ---- commands::touch::change_file_mtime_to_reference stdout ---- === stderr thread 'commands::touch::change_file_mtime_to_reference' panicked at crates/nu-command/tests/commands/touch.rs:298:9: assertion `left == right` failed left: SystemTime { tv_sec: 1719149697, tv_nsec: 57576929 } right: SystemTime { tv_sec: 1719149697, tv_nsec: 78219489 } failures: commands::touch::change_file_mtime_to_reference test result: FAILED. 1533 passed; 1 failed; 32 ignored; 0 measured; 0 filtered out; finished in 10.87s error: test failed, to rerun pass `-p nu-command --test main` - :green_circle: `toolkit fmt` - :green_circle: `toolkit clippy` - :red_circle: `toolkit test` - :black_circle: `toolkit test stdlib` ``` # After Submitting nothing --- .../nu-command/src/formats/from/delimited.rs | 2 +- crates/nu-command/src/formats/from/ssv.rs | 44 +++++++++---------- .../tests/format_conversions/csv.rs | 2 +- .../tests/format_conversions/ssv.rs | 4 +- .../tests/format_conversions/tsv.rs | 2 +- 5 files changed, 27 insertions(+), 27 deletions(-) diff --git a/crates/nu-command/src/formats/from/delimited.rs b/crates/nu-command/src/formats/from/delimited.rs index 853f3bd83e..8f84890645 100644 --- a/crates/nu-command/src/formats/from/delimited.rs +++ b/crates/nu-command/src/formats/from/delimited.rs @@ -39,7 +39,7 @@ fn from_delimited_stream( .from_reader(input_reader); let headers = if noheaders { - (1..=reader + (0..reader .headers() .map_err(|err| from_csv_error(err, span))? .len()) diff --git a/crates/nu-command/src/formats/from/ssv.rs b/crates/nu-command/src/formats/from/ssv.rs index 5efb2a6c3b..1d17dfc69d 100644 --- a/crates/nu-command/src/formats/from/ssv.rs +++ b/crates/nu-command/src/formats/from/ssv.rs @@ -52,12 +52,12 @@ impl Command for FromSsv { Value::test_list( vec![ Value::test_record(record! { - "column1" => Value::test_string("FOO"), - "column2" => Value::test_string("BAR"), + "column0" => Value::test_string("FOO"), + "column1" => Value::test_string("BAR"), }), Value::test_record(record! { - "column1" => Value::test_string("1"), - "column2" => Value::test_string("2"), + "column0" => Value::test_string("1"), + "column1" => Value::test_string("2"), }), ], ) @@ -170,7 +170,7 @@ fn parse_aligned_columns<'a>( let headers: Vec<(String, usize)> = indices .iter() .enumerate() - .map(|(i, position)| (format!("column{}", i + 1), *position)) + .map(|(i, position)| (format!("column{}", i), *position)) .collect(); construct(ls.iter().map(|s| s.to_owned()), headers) @@ -215,7 +215,7 @@ fn parse_separated_columns<'a>( let parse_without_headers = |ls: Vec<&str>| { let num_columns = ls.iter().map(|r| r.len()).max().unwrap_or(0); - let headers = (1..=num_columns) + let headers = (0..=num_columns) .map(|i| format!("column{i}")) .collect::>(); collect(headers, ls.into_iter(), separator) @@ -370,9 +370,9 @@ mod tests { assert_eq!( result, vec![ - vec![owned("column1", "a"), owned("column2", "b")], - vec![owned("column1", "1"), owned("column2", "2")], - vec![owned("column1", "3"), owned("column2", "4")] + vec![owned("column0", "a"), owned("column1", "b")], + vec![owned("column0", "1"), owned("column1", "2")], + vec![owned("column0", "3"), owned("column1", "4")] ] ); } @@ -484,25 +484,25 @@ mod tests { result, vec![ vec![ - owned("column1", "a multi-word value"), - owned("column2", "b"), - owned("column3", ""), - owned("column4", "d"), - owned("column5", "") - ], - vec![ - owned("column1", "1"), + owned("column0", "a multi-word value"), + owned("column1", "b"), owned("column2", ""), - owned("column3", "3-3"), - owned("column4", "4"), - owned("column5", "") + owned("column3", "d"), + owned("column4", "") ], vec![ + owned("column0", "1"), + owned("column1", ""), + owned("column2", "3-3"), + owned("column3", "4"), + owned("column4", "") + ], + vec![ + owned("column0", ""), owned("column1", ""), owned("column2", ""), owned("column3", ""), - owned("column4", ""), - owned("column5", "last") + owned("column4", "last") ], ] ); diff --git a/crates/nu-command/tests/format_conversions/csv.rs b/crates/nu-command/tests/format_conversions/csv.rs index a9be76d5c3..f10a84b672 100644 --- a/crates/nu-command/tests/format_conversions/csv.rs +++ b/crates/nu-command/tests/format_conversions/csv.rs @@ -284,7 +284,7 @@ fn from_csv_text_skipping_headers_to_table() { r#" open los_tres_amigos.txt | from csv --noheaders - | get column3 + | get column2 | length "# )); diff --git a/crates/nu-command/tests/format_conversions/ssv.rs b/crates/nu-command/tests/format_conversions/ssv.rs index a673b122fb..5a62f796f7 100644 --- a/crates/nu-command/tests/format_conversions/ssv.rs +++ b/crates/nu-command/tests/format_conversions/ssv.rs @@ -74,7 +74,7 @@ fn from_ssv_text_treating_first_line_as_data_with_flag() { open oc_get_svc.txt | from ssv --noheaders -a | first - | get column1 + | get column0 "# )); @@ -84,7 +84,7 @@ fn from_ssv_text_treating_first_line_as_data_with_flag() { open oc_get_svc.txt | from ssv --noheaders | first - | get column1 + | get column0 "# )); diff --git a/crates/nu-command/tests/format_conversions/tsv.rs b/crates/nu-command/tests/format_conversions/tsv.rs index be57c60242..31740ef8d9 100644 --- a/crates/nu-command/tests/format_conversions/tsv.rs +++ b/crates/nu-command/tests/format_conversions/tsv.rs @@ -207,7 +207,7 @@ fn from_tsv_text_skipping_headers_to_table() { r#" open los_tres_amigos.txt | from tsv --noheaders - | get column3 + | get column2 | length "# )); From 46ed69ab126015375d5163972ae321715f34874b Mon Sep 17 00:00:00 2001 From: Bruce Weirdan Date: Thu, 27 Jun 2024 01:49:44 +0200 Subject: [PATCH 15/16] Add `char nul` (#13241) # Description Adds `char nul`, `char null_byte` and `char zero_byte` named characters. All of them generate 0x00 byte. # User-Facing Changes Three new named characters are added: * `char nul` - generates 0x00 byte * `char null_byte` - generates 0x00 byte * `char zero_byte` - generates 0x00 byte --- crates/nu-command/src/strings/char_.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/nu-command/src/strings/char_.rs b/crates/nu-command/src/strings/char_.rs index dd7b5cf39b..6834134b26 100644 --- a/crates/nu-command/src/strings/char_.rs +++ b/crates/nu-command/src/strings/char_.rs @@ -19,6 +19,9 @@ static CHAR_MAP: Lazy> = Lazy::new(|| { // These are some regular characters that either can't be used or // it's just easier to use them like this. + "nul" => '\x00'.to_string(), // nul character, 0x00 + "null_byte" => '\x00'.to_string(), // nul character, 0x00 + "zero_byte" => '\x00'.to_string(), // nul character, 0x00 // This are the "normal" characters section "newline" => '\n'.to_string(), "enter" => '\n'.to_string(), From 0d79b637118ac53f27a829fdfbd930f434a6bf0e Mon Sep 17 00:00:00 2001 From: suimong Date: Thu, 27 Jun 2024 22:46:10 +0800 Subject: [PATCH 16/16] Fix find command output bug in the case of taking ByteStream input. (#13246) fixes #13245 # Description In addition to addressing #13245, this PR also updated one of the doc example to the `find` command to document that non-regex mode is case insensitive, which may surprise some users. # User-Facing Changes # Tests + Formatting - :green_circle: `toolkit fmt` - :green_circle: `toolkit clippy` - :green_circle: `toolkit test` - :green_circle: `toolkit test stdlib` # After Submitting --------- Co-authored-by: Ben Yang Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com> --- crates/nu-command/src/filters/find.rs | 11 ++++++----- crates/nu-command/tests/commands/find.rs | 10 ++++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/nu-command/src/filters/find.rs b/crates/nu-command/src/filters/find.rs index dfdef66969..af626c1e75 100644 --- a/crates/nu-command/src/filters/find.rs +++ b/crates/nu-command/src/filters/find.rs @@ -69,9 +69,9 @@ impl Command for Find { result: None, }, Example { - description: "Search and highlight text for a term in a string", - example: r#"'Cargo.toml' | find toml"#, - result: Some(Value::test_string("\u{1b}[37mCargo.\u{1b}[0m\u{1b}[41;37mtoml\u{1b}[0m\u{1b}[37m\u{1b}[0m".to_owned())), + description: "Search and highlight text for a term in a string. Note that regular search is case insensitive", + example: r#"'Cargo.toml' | find cargo"#, + result: Some(Value::test_string("\u{1b}[37m\u{1b}[0m\u{1b}[41;37mCargo\u{1b}[0m\u{1b}[37m.toml\u{1b}[0m".to_owned())), }, Example { description: "Search a number or a file size in a list of numbers", @@ -457,9 +457,10 @@ fn find_with_rest_and_highlight( let mut output: Vec = vec![]; for line in lines { - let line = line?.to_lowercase(); + let line = line?; + let lower_val = line.to_lowercase(); for term in &terms { - if line.contains(term) { + if lower_val.contains(term) { output.push(Value::string( highlight_search_string( &line, diff --git a/crates/nu-command/tests/commands/find.rs b/crates/nu-command/tests/commands/find.rs index ed811f2a57..89bf2d9f39 100644 --- a/crates/nu-command/tests/commands/find.rs +++ b/crates/nu-command/tests/commands/find.rs @@ -17,6 +17,16 @@ fn find_with_list_search_with_char() { assert_eq!(actual.out, "[\"\\u001b[37m\\u001b[0m\\u001b[41;37ml\\u001b[0m\\u001b[37marry\\u001b[0m\",\"\\u001b[37mcur\\u001b[0m\\u001b[41;37ml\\u001b[0m\\u001b[37my\\u001b[0m\"]"); } +#[test] +fn find_with_bytestream_search_with_char() { + let actual = + nu!("\"ABC\" | save foo.txt; let res = open foo.txt | find abc; rm foo.txt; $res | get 0"); + assert_eq!( + actual.out, + "\u{1b}[37m\u{1b}[0m\u{1b}[41;37mABC\u{1b}[0m\u{1b}[37m\u{1b}[0m" + ) +} + #[test] fn find_with_list_search_with_number() { let actual = nu!("[1 2 3 4 5] | find 3 | get 0");