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

503 lines
10 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 {
2021-10-25 08:31:39 +02:00
let mut engine_state = EngineState::new();
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);
// Core
bind_command! {
2021-10-10 22:24:54 +02:00
Alias,
Ast,
Break,
Commandline,
Const,
Continue,
Debug,
2021-10-10 22:24:54 +02:00
Def,
DefEnv,
Describe,
2021-10-10 22:24:54 +02:00
Do,
Echo,
ErrorMake,
ExportAlias,
ExportCommand,
2021-10-10 22:24:54 +02:00
ExportDef,
ExportDefEnv,
ExportExtern,
ExportUse,
Extern,
2021-10-10 22:24:54 +02:00
For,
Help,
2022-12-30 16:44:37 +01:00
HelpAliases,
HelpCommands,
HelpModules,
HelpOperators,
2021-10-10 22:24:54 +02:00
Hide,
HideEnv,
2021-10-10 22:24:54 +02:00
If,
Ignore,
Overlays (#5375) * WIP: Start laying overlays * Rename Overlay->Module; Start adding overlay * Revamp adding overlay * Add overlay add tests; Disable debug print * Fix overlay add; Add overlay remove * Add overlay remove tests * Add missing overlay remove file * Add overlay list command * (WIP?) Enable overlays for env vars * Move OverlayFrames to ScopeFrames * (WIP) Move everything to overlays only ScopeFrame contains nothing but overlays now * Fix predecls * Fix wrong overlay id translation and aliases * Fix broken env lookup logic * Remove TODOs * Add overlay add + remove for environment * Add a few overlay tests; Fix overlay add name * Some cleanup; Fix overlay add/remove names * Clippy * Fmt * Remove walls of comments * List overlays from stack; Add debugging flag Currently, the engine state ordering is somehow broken. * Fix (?) overlay list test * Fix tests on Windows * Fix activated overlay ordering * Check for active overlays equality in overlay list This removes the -p flag: Either both parser and engine will have the same overlays, or the command will fail. * Add merging on overlay remove * Change help message and comment * Add some remove-merge/discard tests * (WIP) Track removed overlays properly * Clippy; Fmt * Fix getting last overlay; Fix predecls in overlays * Remove merging; Fix re-add overwriting stuff Also some error message tweaks. * Fix overlay error in the engine * Update variable_completions.rs * Adds flags and optional arguments to view-source (#5446) * added flags and optional arguments to view-source * removed redundant code * removed redundant code * fmt * fix bug in shell_integration (#5450) * fix bug in shell_integration * add some comments * enable cd to work with directory abbreviations (#5452) * enable cd to work with abbreviations * add abbreviation example * fix tests * make it configurable * make cd recornize symblic link (#5454) * implement seq char command to generate single character sequence (#5453) * add tmp code * add seq char command * Add split number flag in `split row` (#5434) Signed-off-by: Yuheng Su <gipsyh.icu@gmail.com> * Add two more overlay tests * Add ModuleId to OverlayFrame * Fix env conversion accidentally activating overlay It activated overlay from permanent state prematurely which would cause `overlay add` to misbehave. * Remove unused parameter; Add overlay list test * Remove added traces * Add overlay commands examples * Modify TODO * Fix $nu.scope iteration * Disallow removing default overlay * Refactor some parser errors * Remove last overlay if no argument * Diversify overlay examples * Make it possible to update overlay's module In case the origin module updates, the overlay add loads the new module, makes it overlay's origin and applies the changes. Before, it was impossible to update the overlay if the module changed. Co-authored-by: JT <547158+jntrnr@users.noreply.github.com> Co-authored-by: pwygab <88221256+merelymyself@users.noreply.github.com> Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com> Co-authored-by: WindSoilder <WindSoilder@outlook.com> Co-authored-by: Yuheng Su <gipsyh.icu@gmail.com>
2022-05-07 21:39:22 +02:00
Overlay,
OverlayUse,
Overlays (#5375) * WIP: Start laying overlays * Rename Overlay->Module; Start adding overlay * Revamp adding overlay * Add overlay add tests; Disable debug print * Fix overlay add; Add overlay remove * Add overlay remove tests * Add missing overlay remove file * Add overlay list command * (WIP?) Enable overlays for env vars * Move OverlayFrames to ScopeFrames * (WIP) Move everything to overlays only ScopeFrame contains nothing but overlays now * Fix predecls * Fix wrong overlay id translation and aliases * Fix broken env lookup logic * Remove TODOs * Add overlay add + remove for environment * Add a few overlay tests; Fix overlay add name * Some cleanup; Fix overlay add/remove names * Clippy * Fmt * Remove walls of comments * List overlays from stack; Add debugging flag Currently, the engine state ordering is somehow broken. * Fix (?) overlay list test * Fix tests on Windows * Fix activated overlay ordering * Check for active overlays equality in overlay list This removes the -p flag: Either both parser and engine will have the same overlays, or the command will fail. * Add merging on overlay remove * Change help message and comment * Add some remove-merge/discard tests * (WIP) Track removed overlays properly * Clippy; Fmt * Fix getting last overlay; Fix predecls in overlays * Remove merging; Fix re-add overwriting stuff Also some error message tweaks. * Fix overlay error in the engine * Update variable_completions.rs * Adds flags and optional arguments to view-source (#5446) * added flags and optional arguments to view-source * removed redundant code * removed redundant code * fmt * fix bug in shell_integration (#5450) * fix bug in shell_integration * add some comments * enable cd to work with directory abbreviations (#5452) * enable cd to work with abbreviations * add abbreviation example * fix tests * make it configurable * make cd recornize symblic link (#5454) * implement seq char command to generate single character sequence (#5453) * add tmp code * add seq char command * Add split number flag in `split row` (#5434) Signed-off-by: Yuheng Su <gipsyh.icu@gmail.com> * Add two more overlay tests * Add ModuleId to OverlayFrame * Fix env conversion accidentally activating overlay It activated overlay from permanent state prematurely which would cause `overlay add` to misbehave. * Remove unused parameter; Add overlay list test * Remove added traces * Add overlay commands examples * Modify TODO * Fix $nu.scope iteration * Disallow removing default overlay * Refactor some parser errors * Remove last overlay if no argument * Diversify overlay examples * Make it possible to update overlay's module In case the origin module updates, the overlay add loads the new module, makes it overlay's origin and applies the changes. Before, it was impossible to update the overlay if the module changed. Co-authored-by: JT <547158+jntrnr@users.noreply.github.com> Co-authored-by: pwygab <88221256+merelymyself@users.noreply.github.com> Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com> Co-authored-by: WindSoilder <WindSoilder@outlook.com> Co-authored-by: Yuheng Su <gipsyh.icu@gmail.com>
2022-05-07 21:39:22 +02:00
OverlayList,
OverlayNew,
OverlayHide,
Let,
Loop,
Metadata,
Module,
Mut,
Return,
Try,
Use,
Version,
2022-11-11 19:21:45 +01:00
While,
};
// Charts
bind_command! {
Histogram
}
// Filters
bind_command! {
All,
Any,
Append,
Collect,
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,
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! {
Benchmark,
Complete,
External,
NuCheck,
Sys,
};
#[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,
StrLpad,
StrPascalCase,
StrReverse,
StrRpad,
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,
FromEml,
FromIcs,
FromIni,
FromJson,
FromNuon,
FromOds,
FromSsv,
FromToml,
FromTsv,
FromUrl,
FromVcf,
FromXlsx,
FromXml,
FromYaml,
FromYml,
2021-10-29 08:26:29 +02:00
To,
ToCsv,
ToHtml,
ToJson,
ToMd,
ToNuon,
ToText,
ToToml,
ToTsv,
Touch,
Use,
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! {
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! {
2022-01-16 00:50:11 +01:00
Env,
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,
HttpGet,
HttpPost,
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! {
ViewSource,
IsAdmin,
};
// Deprecated
bind_command! {
HashBase64,
Source,
StrDatetimeDeprecated,
StrDecimalDeprecated,
StrIntDeprecated,
StrFindReplaceDeprecated,
MathEvalDeprecated,
};
2021-11-02 21:56:00 +01:00
#[cfg(feature = "plugin")]
bind_command!(Register);
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
}