nushell/crates/nu-command/src/default_context.rs

465 lines
9.5 KiB
Rust
Raw Normal View History

2021-11-26 09:00:57 +01:00
use nu_protocol::engine::{EngineState, StateWorkingSet};
2021-09-03 00:58:15 +02:00
2021-10-02 04:59:11 +02:00
use crate::*;
2021-09-03 00:58:15 +02:00
pub fn create_default_context() -> EngineState {
let mut engine_state = nu_cmd_lang::create_default_context();
2021-10-28 06:13:10 +02:00
2021-09-03 00:58:15 +02:00
let delta = {
2021-10-25 08:31:39 +02:00
let mut working_set = StateWorkingSet::new(&engine_state);
2021-09-03 00:58:15 +02:00
macro_rules! bind_command {
( $( $command:expr ),* $(,)? ) => {
$( working_set.add_decl(Box::new($command)); )*
};
}
2021-09-23 21:03:08 +02:00
// If there are commands that have the same name as default declarations,
// they have to be registered before the main declarations. This helps to make
// them only accessible if the correct input value category is used with the
// declaration
#[cfg(feature = "dataframe")]
add_dataframe_decls(&mut working_set);
// Database-related
// Adds all related commands to query databases
#[cfg(feature = "sqlite")]
add_database_decls(&mut working_set);
// Charts
bind_command! {
Histogram
}
// Filters
bind_command! {
All,
Any,
Append,
Columns,
Compact,
2022-01-25 16:02:15 +01:00
Default,
Drop,
DropColumn,
2021-12-15 13:26:15 +01:00
DropNth,
Each,
EachWhile,
Empty,
Add 'number' command for enumeration (#7871) # Description This adds a `number` command that will enumerate the input, and add an `index` and `item` record for each item. The `index` is the number of the item in the input stream, and `item` is the original value of the item. ``` > ls | number | get 14 ╭───────┬────────────────────────────╮ │ index │ 14 │ │ │ ╭──────────┬─────────────╮ │ │ item │ │ name │ crates │ │ │ │ │ type │ dir │ │ │ │ │ size │ 832 B │ │ │ │ │ modified │ 2 weeks ago │ │ │ │ ╰──────────┴─────────────╯ │ ╰───────┴────────────────────────────╯ ``` # User-Facing Changes This adds a `number` command. # Tests + Formatting Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style - `cargo test --workspace` to check that all tests pass # After Submitting If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date.
2023-01-27 18:45:57 +01:00
Enumerate,
2021-12-31 00:41:18 +01:00
Every,
Filter,
Find,
First,
Flatten,
Get,
Group,
GroupBy,
Headers,
2022-03-17 18:55:02 +01:00
Insert,
SQL-style join command for Nushell tables (#8424) This PR adds a command `join` for performing SQL-style joins on Nushell tables: ``` 〉join -h Join two tables Usage: > join {flags} <right-table> <left-on> (right-on) Flags: -h, --help - Display the help message for this command -i, --inner - Inner join (default) -l, --left - Left-outer join -r, --right - Right-outer join -o, --outer - Outer join Signatures: <table> | join list<any>, <string>, <string?> -> <table> Parameters: right-table <list<any>>: The right table in the join left-on <string>: Name of column in input (left) table to join on (optional) right-on <string>: Name of column in right table to join on. Defaults to same column as left table. Examples: Join two tables > [{a: 1 b: 2}] | join [{a: 1 c: 3}] a ╭───┬───┬───╮ │ a │ b │ c │ ├───┼───┼───┤ │ 1 │ 2 │ 3 │ ╰───┴───┴───╯ ``` <table> <tbody> <tr> <td><img width="400" alt="image" src="https://user-images.githubusercontent.com/52205/224578744-eb9d133e-2510-4a3d-bd0a-d615f07a06b7.png"></td> </tr> </tbody> </table> # User-Facing Changes Adds a new command `join` # Tests + Formatting ``` cargo test -p nu-command commands::join ``` Don't forget to add tests that cover your changes. - [x] `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - [x] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style - [x] `cargo test --workspace` to check that all tests pass # After Submitting - [ ] If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date. --------- Co-authored-by: Reilly Wood <reilly.wood@icloud.com>
2023-03-17 00:57:20 +01:00
Join,
2022-01-31 00:29:21 +01:00
SplitBy,
2022-04-07 22:49:28 +02:00
Take,
Merge,
Move,
2022-04-07 22:49:28 +02:00
TakeWhile,
TakeUntil,
Last,
2021-10-10 22:24:54 +02:00
Length,
Lines,
2021-10-26 03:30:53 +02:00
ParEach,
Prepend,
Range,
Reduce,
Reject,
Rename,
Reverse,
Roll,
RollDown,
RollUp,
RollLeft,
RollRight,
Rotate,
2021-10-10 22:24:54 +02:00
Select,
Shuffle,
Skip,
SkipUntil,
SkipWhile,
2022-04-01 00:43:16 +02:00
Sort,
SortBy,
SplitList,
Transpose,
Uniq,
UniqBy,
Upsert,
2022-03-17 18:55:02 +01:00
Update,
UpdateCells,
Values,
Where,
Window,
Wrap,
Zip,
};
// Misc
bind_command! {
History,
Tutor,
2022-09-19 21:30:04 +02:00
HistorySession,
};
// Path
bind_command! {
Path,
PathBasename,
PathDirname,
PathExists,
PathExpand,
PathJoin,
PathParse,
PathRelativeTo,
PathSplit,
PathType,
};
// System
bind_command! {
Complete,
External,
NuCheck,
Sys,
};
// Debug
bind_command! {
Ast,
Debug,
Explain,
Inspect,
Metadata,
Profile,
TimeIt,
View,
ViewFiles,
ViewSource,
ViewSpan,
};
#[cfg(unix)]
bind_command! { Exec }
#[cfg(windows)]
bind_command! { RegistryQuery }
#[cfg(any(
target_os = "android",
target_os = "linux",
target_os = "macos",
target_os = "windows"
))]
bind_command! { Ps };
#[cfg(feature = "which-support")]
bind_command! { Which };
// Strings
bind_command! {
Char,
Decode,
Encode,
DecodeBase64,
EncodeBase64,
2022-01-30 13:52:24 +01:00
DetectColumns,
Format,
FileSize,
Parse,
Size,
2021-10-10 22:24:54 +02:00
Split,
SplitChars,
SplitColumn,
SplitRow,
SplitWords,
Str,
StrCamelCase,
StrCapitalize,
StrCollect,
StrContains,
StrDistance,
StrDowncase,
StrEndswith,
StrJoin,
StrReplace,
StrIndexOf,
StrKebabCase,
StrLength,
StrPascalCase,
StrReverse,
StrScreamingSnakeCase,
StrSnakeCase,
StrStartsWith,
StrSubstring,
2021-12-02 05:38:44 +01:00
StrTrim,
StrTitleCase,
StrUpcase
};
// Bits
bind_command! {
Bits,
BitsAnd,
BitsNot,
BitsOr,
BitsXor,
BitsRotateLeft,
BitsRotateRight,
BitsShiftLeft,
BitsShiftRight,
}
2022-07-04 12:51:07 +02:00
// Bytes
bind_command! {
Bytes,
BytesLen,
BytesStartsWith,
BytesEndsWith,
BytesReverse,
BytesReplace,
2022-07-09 04:42:31 +02:00
BytesAdd,
BytesAt,
BytesIndexOf,
BytesCollect,
BytesRemove,
BytesBuild,
2022-07-04 12:51:07 +02:00
}
// FileSystem
bind_command! {
Cd,
Cp,
Ls,
Mkdir,
Mv,
2021-12-24 20:24:55 +01:00
Open,
Start,
Rm,
Save,
Touch,
2022-04-04 22:45:01 +02:00
Glob,
2022-04-28 16:26:34 +02:00
Watch,
};
// Platform
bind_command! {
Ansi,
AnsiGradient,
AnsiStrip,
2023-01-15 16:23:37 +01:00
AnsiLink,
Clear,
Du,
KeybindingsDefault,
Input,
KeybindingsListen,
Keybindings,
Kill,
KeybindingsList,
Sleep,
TermSize,
};
// Date
bind_command! {
Date,
DateFormat,
DateHumanize,
DateListTimezones,
DateNow,
2022-04-01 10:09:30 +02:00
DateToRecord,
DateToTable,
DateToTimezone,
};
// Shells
bind_command! {
2022-01-05 05:35:50 +01:00
Enter,
Exit,
2022-01-05 05:35:50 +01:00
GotoShell,
NextShell,
PrevShell,
Shells,
};
// Formats
bind_command! {
From,
FromCsv,
FromJson,
FromNuon,
FromOds,
FromSsv,
FromToml,
FromTsv,
FromUrl,
FromXlsx,
FromXml,
FromYaml,
FromYml,
2021-10-29 08:26:29 +02:00
To,
ToCsv,
ToHtml,
ToJson,
ToMd,
ToNuon,
ToText,
ToToml,
ToTsv,
Touch,
Upsert,
Where,
2021-12-10 21:46:43 +01:00
ToXml,
ToYaml,
};
// Viewers
bind_command! {
Griddle,
Table,
[MVP][WIP] `less` like pager (#6984) Run it as `explore`. #### example ```nu ls | explore ``` Configuration points in `config.nu` file. ``` # A 'explore' utility config explore_config: { highlight: { bg: 'yellow', fg: 'black' } status_bar: { bg: '#C4C9C6', fg: '#1D1F21' } command_bar: { fg: '#C4C9C6' } split_line: '#404040' cursor: true # selected_column: 'blue' # selected_row: { fg: 'yellow', bg: '#C1C2A3' } # selected_cell: { fg: 'white', bg: '#777777' } # line_shift: false, # line_index: false, # line_head_top: false, # line_head_bottom: false, } ``` You can start without a pipeline and type `explore` and it'll give you a few tips. ![image](https://user-images.githubusercontent.com/343840/205088971-a8c0262f-f222-4641-b13a-027fbd4f5e1a.png) If you type `:help` you an see the help screen with some information on what tui keybindings are available. ![image](https://user-images.githubusercontent.com/343840/205089461-c4c54217-7ec4-4fa0-96c0-643d68dc0062.png) From the `:help` screen you can now hit `i` and that puts you in `cursor` aka `inspection` mode and you can move the cursor left right up down and it you put it on an area such as `[table 5 rows]` and hit the enter key, you'll see something like this, which shows all the `:` commands. If you hit `esc` it will take you to the previous screen. ![image](https://user-images.githubusercontent.com/343840/205090155-3558a14b-87b7-4072-8dfb-dc8cc2ef4943.png) If you then type `:try` you'll get this type of window where you can type in the top portion and see results in the bottom. ![image](https://user-images.githubusercontent.com/343840/205089185-3c065551-0792-43d6-a13c-a52762856209.png) The `:nu` command is interesting because you can type pipelines like `:nu ls | sort-by type size` or another pipeline of your choosing such as `:nu sys` and that will show the table that looks like this, which we're calling "table mode". ![image](https://user-images.githubusercontent.com/343840/205090809-e686ff0f-6d0b-4347-8ed0-8c59adfbd741.png) If you hit the `t` key it will now transpose the view to look like this. ![image](https://user-images.githubusercontent.com/343840/205090948-a834d7f2-1713-4dfe-92fe-5432f287df3d.png) In table mode or transposed table mode you can use the `i` key to inspect any collapsed field like `{record 8 fields}`, `[table 16 rows]`, `[list x]`, etc. One of the original benefits was that when you're in a view that has a lot of columns, `explore` gives you the ability to scroll left, right, up, and down. `explore` is also smart enough to know when you're in table mode versus preview mode. If you do `open Cargo.toml | explore` you get this. ![image](https://user-images.githubusercontent.com/343840/205091822-cac79130-3a52-4ca8-9210-eba5be30ed58.png) If you type `open --raw Cargo.toml | explore` you get this where you can scroll left, right, up, down. This is called preview mode. ![image](https://user-images.githubusercontent.com/343840/205091990-69455191-ab78-4fea-a961-feafafc16d70.png) When you're in table mode, you can also type `:preview`. So, with `open --raw Cargo.toml | explore`, if you type `:preview`, it will look like this. ![image](https://user-images.githubusercontent.com/343840/205092569-436aa55a-0474-48d5-ab71-baddb1f43027.png) Signed-off-by: Maxim Zhiburt <zhiburt@gmail.com> Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2022-12-01 16:32:10 +01:00
Explore,
};
// Conversions
bind_command! {
A `fill` command to replace `str lpad` and `str rpad` (#7846) # Description The point of this command is to allow you to be able to format ints, floats, filesizes, and strings with an alignment, padding, and a fill character, as strings. It's meant to take the place of `str lpad` and `str rpad`. ``` > help fill Fill and Align Search terms: display, render, format, pad, align Usage: > fill {flags} Flags: -h, --help - Display the help message for this command -w, --width <Int> - The width of the output. Defaults to 1 -a, --alignment <String> - The alignment of the output. Defaults to Left (Left(l), Right(r), Center(c/m), MiddleRight(cr/mr)) -c, --character <String> - The character to fill with. Defaults to ' ' (space) Signatures: <number> | fill -> <string> <string> | fill -> <string> Examples: Fill a string on the left side to a width of 15 with the character '─' > 'nushell' | fill -a l -c '─' -w 15 Fill a string on the right side to a width of 15 with the character '─' > 'nushell' | fill -a r -c '─' -w 15 Fill a string on both sides to a width of 15 with the character '─' > 'nushell' | fill -a m -c '─' -w 15 Fill a number on the left side to a width of 5 with the character '0' > 1 | fill --alignment right --character 0 --width 5 Fill a filesize on the left side to a width of 5 with the character '0' > 1kib | fill --alignment middle --character 0 --width 10 ``` ![image](https://user-images.githubusercontent.com/343840/214133752-6fc93fa7-4003-4eb4-96ed-cd967312e244.png) # User-Facing Changes Deprecated `str lpad` and `str rpad`. # Tests + Formatting Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style - `cargo test --workspace` to check that all tests pass # After Submitting If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date.
2023-02-09 21:56:52 +01:00
Fill,
2022-01-16 00:50:11 +01:00
Fmt,
Into,
IntoBool,
IntoBinary,
IntoDatetime,
IntoDecimal,
IntoDuration,
IntoFilesize,
IntoInt,
add `into record` command (#7225) # Description This command converts things into records. <img width="466" alt="Screenshot 2022-11-24 at 2 10 54 PM" src="https://user-images.githubusercontent.com/343840/203858104-0e4445da-9c37-4c7c-97ec-68ec3515bc4b.png"> <img width="716" alt="Screenshot 2022-11-24 at 5 04 11 PM" src="https://user-images.githubusercontent.com/343840/203872621-48cab199-ba57-44fe-8f36-9e1469b9c4ef.png"> It also converts dates into record but I couldn't get the test harness to accept an example. Thanks to @WindSoilder for writing the "hard" parts of this. :) _(Thank you for improving Nushell. Please, check our [contributing guide](../CONTRIBUTING.md) and talk to the core team before making major changes.)_ _(Description of your pull request goes here. **Provide examples and/or screenshots** if your changes affect the user experience.)_ # User-Facing Changes _(List of all changes that impact the user experience here. This helps us keep track of breaking changes.)_ # Tests + Formatting Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style - `cargo test --workspace` to check that all tests pass # After Submitting If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date. Co-authored-by: WindSoilder <WindSoilder@outlook.com>
2022-11-26 16:00:47 +01:00
IntoRecord,
IntoString,
};
// Env
bind_command! {
ExportEnv,
LetEnv,
2022-01-16 00:50:11 +01:00
LoadEnv,
SourceEnv,
2021-11-04 03:32:35 +01:00
WithEnv,
ConfigNu,
ConfigEnv,
ConfigMeta,
ConfigReset,
};
// Math
bind_command! {
Math,
MathAbs,
MathAvg,
MathCeil,
MathFloor,
MathMax,
MathMedian,
MathMin,
MathMode,
MathProduct,
MathRound,
MathSqrt,
MathStddev,
MathSum,
MathVariance,
MathSin,
MathCos,
MathTan,
MathSinH,
MathCosH,
MathTanH,
MathArcSin,
MathArcCos,
MathArcTan,
MathArcSinH,
MathArcCosH,
MathArcTanH,
MathPi,
MathTau,
MathEuler,
MathLn,
MathLog,
};
// Network
bind_command! {
Http,
HttpDelete,
HttpGet,
HttpHead,
HttpPatch,
HttpPost,
HttpPut,
Url,
UrlBuildQuery,
UrlEncode,
UrlJoin,
UrlParse,
Port,
}
// Random
bind_command! {
Random,
RandomBool,
RandomChars,
RandomDecimal,
RandomDice,
RandomInteger,
RandomUuid,
};
// Generators
bind_command! {
Cal,
Seq,
SeqDate,
SeqChar,
};
// Hash
bind_command! {
Hash,
HashMd5::default(),
HashSha256::default(),
};
2021-09-03 04:15:01 +02:00
// Experimental
bind_command! {
IsAdmin,
};
// Deprecated
bind_command! {
HashBase64,
A `fill` command to replace `str lpad` and `str rpad` (#7846) # Description The point of this command is to allow you to be able to format ints, floats, filesizes, and strings with an alignment, padding, and a fill character, as strings. It's meant to take the place of `str lpad` and `str rpad`. ``` > help fill Fill and Align Search terms: display, render, format, pad, align Usage: > fill {flags} Flags: -h, --help - Display the help message for this command -w, --width <Int> - The width of the output. Defaults to 1 -a, --alignment <String> - The alignment of the output. Defaults to Left (Left(l), Right(r), Center(c/m), MiddleRight(cr/mr)) -c, --character <String> - The character to fill with. Defaults to ' ' (space) Signatures: <number> | fill -> <string> <string> | fill -> <string> Examples: Fill a string on the left side to a width of 15 with the character '─' > 'nushell' | fill -a l -c '─' -w 15 Fill a string on the right side to a width of 15 with the character '─' > 'nushell' | fill -a r -c '─' -w 15 Fill a string on both sides to a width of 15 with the character '─' > 'nushell' | fill -a m -c '─' -w 15 Fill a number on the left side to a width of 5 with the character '0' > 1 | fill --alignment right --character 0 --width 5 Fill a filesize on the left side to a width of 5 with the character '0' > 1kib | fill --alignment middle --character 0 --width 10 ``` ![image](https://user-images.githubusercontent.com/343840/214133752-6fc93fa7-4003-4eb4-96ed-cd967312e244.png) # User-Facing Changes Deprecated `str lpad` and `str rpad`. # Tests + Formatting Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style - `cargo test --workspace` to check that all tests pass # After Submitting If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date.
2023-02-09 21:56:52 +01:00
LPadDeprecated,
RPadDeprecated,
Source,
StrDatetimeDeprecated,
StrDecimalDeprecated,
StrIntDeprecated,
StrFindReplaceDeprecated,
MathEvalDeprecated,
Re-implement aliases (#8123) # Description This PR adds an alternative alias implementation. Old aliases still work but you need to use `old-alias` instead of `alias`. Instead of replacing spans in the original code and re-parsing, which proved to be extremely error-prone and a constant source of panics, the new implementation creates a new command that references the old command. Consider the new alias defined as `alias ll = ls -l`. The parser creates a new command called `ll` and remembers that it is actually a `ls` command called with the `-l` flag. Then, when the parser sees the `ll` command, it will translate it to `ls -l` and passes to it any parameters that were passed to the call to `ll`. It works quite similar to how known externals defined with `extern` are implemented. The new alias implementation should work the same way as the old aliases, including exporting from modules, referencing both known and unknown externals. It seems to preserve custom completions and pipeline metadata. It is quite robust in most cases but there are some rough edges (see later). Fixes https://github.com/nushell/nushell/issues/7648, https://github.com/nushell/nushell/issues/8026, https://github.com/nushell/nushell/issues/7512, https://github.com/nushell/nushell/issues/5780, https://github.com/nushell/nushell/issues/7754 No effect: https://github.com/nushell/nushell/issues/8122 (we might revisit the completions code after this PR) Should use custom command instead: https://github.com/nushell/nushell/issues/6048 # User-Facing Changes Since aliases are now basically commands, it has some new implications: 1. `alias spam = "spam"` (requires command call) * **workaround**: use `alias spam = echo "spam"` 2. `def foo [] { 'foo' }; alias foo = ls -l` (foo defined more than once) * **workaround**: use different name (commands also have this limitation) 4. `alias ls = (ls | sort-by type name -i)` * **workaround**: Use custom command. _The common issue with this is that it is currently not easy to pass flags through custom commands and command referencing itself will lead to stack overflow. Both of these issues are meant to be addressed._ 5. TODO: Help messages, `which` command, `$nu.scope.aliases`, etc. * Should we treat the aliases as commands or should they be separated from regular commands? 6. Needs better error message and syntax highlight for recursed alias (`alias f = f`) 7. Can't create alias with the same name as existing command (`alias ls = ls -a`) * Might be possible to add support for it (not 100% sure) 8. Standalone `alias` doesn't list aliases anymore 9. Can't alias parser keywords (e.g., stuff like `alias ou = overlay use` won't work) * TODO: Needs a better error message when attempting to do so # Tests + Formatting Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style - `cargo test --workspace` to check that all tests pass # After Submitting If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date.
2023-02-27 08:44:05 +01:00
OldAlias,
ExportOldAlias,
};
2021-09-03 00:58:15 +02:00
working_set.render()
};
if let Err(err) = engine_state.merge_delta(delta) {
eprintln!("Error creating default context: {err:?}");
}
2021-09-03 00:58:15 +02:00
engine_state
}