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

429 lines
8.7 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
Use only $nu.env.PWD for getting the current directory (#587) * Use only $nu.env.PWD for getting current directory Because setting and reading to/from std::env changes the global state shich is problematic if we call `cd` from multiple threads (e.g., in a `par-each` block). With this change, when engine-q starts, it will either inherit existing PWD env var, or create a new one from `std::env::current_dir()`. Otherwise, everything that needs the current directory will get it from `$nu.env.PWD`. Each spawned external command will get its current directory per-process which should be thread-safe. One thing left to do is to patch nu-path for this as well since it uses `std::env::current_dir()` in its expansions. * Rename nu-path functions *_with is not *_relative which should be more descriptive and frees "with" for use in a followup commit. * Clone stack every each iter; Fix some commands Cloning the stack each iteration of `each` makes sure we're not reusing PWD between iterations. Some fixes in commands to make them use the new PWD. * Post-rebase cleanup, fmt, clippy * Change back _relative to _with in nu-path funcs Didn't use the idea I had for the new "_with". * Remove leftover current_dir from rebase * Add cwd sync at merge_delta() This makes sure the parser and completer always have up-to-date cwd. * Always pass absolute path to glob in ls * Do not allow PWD a relative path; Allow recovery Makes it possible to recover PWD by proceeding with the REPL cycle. * Clone stack in each also for byte/string stream * (WIP) Start moving env variables to engine state * (WIP) Move env vars to engine state (ugly) Quick and dirty code. * (WIP) Remove unused mut and args; Fmt * (WIP) Fix dataframe tests * (WIP) Fix missing args after rebase * (WIP) Clone only env vars, not the whole stack * (WIP) Add env var clone to `for` loop as well * Minor edits * Refactor merge_delta() to include stack merging. Less error-prone than doing it manually. * Clone env for each `update` command iteration * Mark env var hidden only when found in eng. state * Fix clippt warnings * Add TODO about env var reading * Do not clone empty environment in loops * Remove extra cwd collection * Split current_dir() into str and path; Fix autocd * Make completions respect PWD env var
2022-01-04 23:30:34 +01:00
use std::path::Path;
2021-10-02 04:59:11 +02:00
use crate::*;
2021-09-03 00:58:15 +02:00
Use only $nu.env.PWD for getting the current directory (#587) * Use only $nu.env.PWD for getting current directory Because setting and reading to/from std::env changes the global state shich is problematic if we call `cd` from multiple threads (e.g., in a `par-each` block). With this change, when engine-q starts, it will either inherit existing PWD env var, or create a new one from `std::env::current_dir()`. Otherwise, everything that needs the current directory will get it from `$nu.env.PWD`. Each spawned external command will get its current directory per-process which should be thread-safe. One thing left to do is to patch nu-path for this as well since it uses `std::env::current_dir()` in its expansions. * Rename nu-path functions *_with is not *_relative which should be more descriptive and frees "with" for use in a followup commit. * Clone stack every each iter; Fix some commands Cloning the stack each iteration of `each` makes sure we're not reusing PWD between iterations. Some fixes in commands to make them use the new PWD. * Post-rebase cleanup, fmt, clippy * Change back _relative to _with in nu-path funcs Didn't use the idea I had for the new "_with". * Remove leftover current_dir from rebase * Add cwd sync at merge_delta() This makes sure the parser and completer always have up-to-date cwd. * Always pass absolute path to glob in ls * Do not allow PWD a relative path; Allow recovery Makes it possible to recover PWD by proceeding with the REPL cycle. * Clone stack in each also for byte/string stream * (WIP) Start moving env variables to engine state * (WIP) Move env vars to engine state (ugly) Quick and dirty code. * (WIP) Remove unused mut and args; Fmt * (WIP) Fix dataframe tests * (WIP) Fix missing args after rebase * (WIP) Clone only env vars, not the whole stack * (WIP) Add env var clone to `for` loop as well * Minor edits * Refactor merge_delta() to include stack merging. Less error-prone than doing it manually. * Clone env for each `update` command iteration * Mark env var hidden only when found in eng. state * Fix clippt warnings * Add TODO about env var reading * Do not clone empty environment in loops * Remove extra cwd collection * Split current_dir() into str and path; Fix autocd * Make completions respect PWD env var
2022-01-04 23:30:34 +01:00
pub fn create_default_context(cwd: impl AsRef<Path>) -> 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 = "database")]
add_database_decls(&mut working_set);
// Core
bind_command! {
2021-10-10 22:24:54 +02:00
Alias,
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,
ExportEnv,
ExportExtern,
Extern,
2021-10-10 22:24:54 +02:00
For,
Help,
Hide,
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,
OverlayAdd,
OverlayList,
OverlayNew,
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
OverlayRemove,
Let,
Metadata,
Module,
Source,
Use,
Version,
};
// 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,
2021-12-31 00:41:18 +01:00
Every,
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,
Transpose,
Uniq,
Upsert,
2022-03-17 18:55:02 +01:00
Update,
UpdateCells,
Where,
Window,
Wrap,
Zip,
};
// Misc
bind_command! {
History,
Tutor,
};
// Path
bind_command! {
Path,
PathBasename,
PathDirname,
PathExists,
PathExpand,
PathJoin,
PathParse,
PathRelativeTo,
PathSplit,
PathType,
};
// System
bind_command! {
Benchmark,
Complete,
Exec,
External,
NuCheck,
Ps,
Sys,
};
#[cfg(feature = "which-support")]
bind_command! { Which };
// Strings
bind_command! {
BuildString,
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,
Str,
StrCamelCase,
StrCapitalize,
StrCollect,
StrContains,
StrDowncase,
StrEndswith,
StrReplace,
StrIndexOf,
StrKebabCase,
StrLength,
StrLpad,
StrPascalCase,
StrReverse,
StrRpad,
StrScreamingSnakeCase,
StrSnakeCase,
StrStartsWith,
StrSubstring,
2021-12-02 05:38:44 +01:00
StrTrim,
StrTitleCase,
StrUpcase
};
2022-07-04 12:51:07 +02:00
// Bytes
bind_command! {
BytesLen,
BytesStartsWith
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,
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,
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,
ToCsv,
Touch,
Use,
Upsert,
Where,
ToUrl,
2021-12-10 21:46:43 +01:00
ToXml,
ToYaml,
};
// Viewers
bind_command! {
Griddle,
Table,
};
// Conversions
bind_command! {
2022-01-16 00:50:11 +01:00
Fmt,
Into,
IntoBool,
IntoBinary,
IntoDatetime,
IntoDecimal,
IntoDuration,
IntoFilesize,
IntoInt,
IntoString,
};
// Env
bind_command! {
2022-01-16 00:50:11 +01:00
Env,
LetEnv,
2022-01-16 00:50:11 +01:00
LoadEnv,
2021-11-04 03:32:35 +01:00
WithEnv,
ConfigNu,
ConfigEnv,
ConfigMeta,
};
// Math
bind_command! {
Math,
MathAbs,
MathAvg,
MathCeil,
MathEval,
MathFloor,
MathMax,
MathMedian,
MathMin,
MathMode,
MathProduct,
MathRound,
MathSqrt,
MathStddev,
MathSum,
MathVariance,
};
// Network
bind_command! {
Fetch,
Post,
Url,
UrlHost,
UrlPath,
UrlQuery,
UrlScheme,
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(),
HashBase64,
};
2021-09-03 04:15:01 +02:00
// Experimental
bind_command! {
ViewSource,
IsAdmin,
};
// Deprecated
bind_command! {
PivotDeprecated,
StrDatetimeDeprecated,
StrDecimalDeprecated,
StrIntDeprecated,
MatchDeprecated,
NthDeprecated,
UnaliasDeprecated,
StrFindReplaceDeprecated,
2022-04-08 00:10:46 +02:00
KeepDeprecated,
KeepUntilDeprecated,
KeepWhileDeprecated,
};
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()
};
Use only $nu.env.PWD for getting the current directory (#587) * Use only $nu.env.PWD for getting current directory Because setting and reading to/from std::env changes the global state shich is problematic if we call `cd` from multiple threads (e.g., in a `par-each` block). With this change, when engine-q starts, it will either inherit existing PWD env var, or create a new one from `std::env::current_dir()`. Otherwise, everything that needs the current directory will get it from `$nu.env.PWD`. Each spawned external command will get its current directory per-process which should be thread-safe. One thing left to do is to patch nu-path for this as well since it uses `std::env::current_dir()` in its expansions. * Rename nu-path functions *_with is not *_relative which should be more descriptive and frees "with" for use in a followup commit. * Clone stack every each iter; Fix some commands Cloning the stack each iteration of `each` makes sure we're not reusing PWD between iterations. Some fixes in commands to make them use the new PWD. * Post-rebase cleanup, fmt, clippy * Change back _relative to _with in nu-path funcs Didn't use the idea I had for the new "_with". * Remove leftover current_dir from rebase * Add cwd sync at merge_delta() This makes sure the parser and completer always have up-to-date cwd. * Always pass absolute path to glob in ls * Do not allow PWD a relative path; Allow recovery Makes it possible to recover PWD by proceeding with the REPL cycle. * Clone stack in each also for byte/string stream * (WIP) Start moving env variables to engine state * (WIP) Move env vars to engine state (ugly) Quick and dirty code. * (WIP) Remove unused mut and args; Fmt * (WIP) Fix dataframe tests * (WIP) Fix missing args after rebase * (WIP) Clone only env vars, not the whole stack * (WIP) Add env var clone to `for` loop as well * Minor edits * Refactor merge_delta() to include stack merging. Less error-prone than doing it manually. * Clone env for each `update` command iteration * Mark env var hidden only when found in eng. state * Fix clippt warnings * Add TODO about env var reading * Do not clone empty environment in loops * Remove extra cwd collection * Split current_dir() into str and path; Fix autocd * Make completions respect PWD env var
2022-01-04 23:30:34 +01:00
let _ = engine_state.merge_delta(delta, None, &cwd);
2021-09-03 00:58:15 +02:00
engine_state
}