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

335 lines
6.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);
// Core
bind_command! {
2021-10-10 22:24:54 +02:00
Alias,
Debug,
2021-10-10 22:24:54 +02:00
Def,
Describe,
2021-10-10 22:24:54 +02:00
Do,
Echo,
ExportCommand,
2021-10-10 22:24:54 +02:00
ExportDef,
ExportEnv,
2021-10-10 22:24:54 +02:00
For,
Help,
Hide,
2021-12-22 12:19:38 +01:00
History,
2021-10-10 22:24:54 +02:00
If,
Ignore,
Let,
Metadata,
Module,
Source,
Use,
Version,
};
// Filters
bind_command! {
All,
Any,
Append,
Collect,
Columns,
Compact,
Drop,
DropColumn,
2021-12-15 13:26:15 +01:00
DropNth,
Each,
Empty,
2021-12-31 00:41:18 +01:00
Every,
First,
Flatten,
Get,
GroupBy,
Keep,
Merge,
KeepUntil,
KeepWhile,
Last,
2021-10-10 22:24:54 +02:00
Length,
Lines,
Nth,
2021-10-26 03:30:53 +02:00
ParEach,
Prepend,
Range,
Reduce,
Reject,
Reverse,
2021-10-10 22:24:54 +02:00
Select,
Shuffle,
Skip,
SkipUntil,
SkipWhile,
SortBy,
Transpose,
Uniq,
Update,
Where,
Wrap,
Zip,
};
// Path
bind_command! {
Path,
PathBasename,
PathDirname,
PathExists,
PathExpand,
PathJoin,
PathParse,
PathRelativeTo,
PathSplit,
PathType,
};
// System
bind_command! {
Benchmark,
External,
Ps,
Sys,
};
#[cfg(feature = "which")]
bind_command! { Which };
// Strings
bind_command! {
BuildString,
Char,
Decode,
Format,
Parse,
Size,
2021-10-10 22:24:54 +02:00
Split,
SplitChars,
SplitColumn,
SplitRow,
Str,
StrCamelCase,
StrCapitalize,
StrCollect,
StrContains,
StrDowncase,
StrEndswith,
StrFindReplace,
StrIndexOf,
StrKebabCase,
StrLength,
StrLpad,
StrPascalCase,
StrReverse,
StrRpad,
StrScreamingSnakeCase,
StrSnakeCase,
StrStartsWith,
StrSubstring,
2021-12-02 05:38:44 +01:00
StrTrim,
StrUpcase
};
// FileSystem
bind_command! {
Cd,
Cp,
Ls,
Mkdir,
Mv,
2021-12-24 20:24:55 +01:00
Open,
Rm,
Save,
Touch,
};
// Platform
bind_command! {
Ansi,
AnsiGradient,
AnsiStrip,
Clear,
Input,
InputKeys,
Kill,
Sleep,
TermSize,
};
// Date
bind_command! {
Date,
DateFormat,
DateHumanize,
DateListTimezones,
DateNow,
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,
FromOds,
FromSsv,
FromToml,
FromTsv,
FromUrl,
FromVcf,
FromXlsx,
FromXml,
FromYaml,
FromYml,
2021-10-29 08:26:29 +02:00
To,
ToCsv,
ToHtml,
ToJson,
ToMd,
ToToml,
ToTsv,
ToCsv,
Touch,
Use,
Update,
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,
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,
};
// Math
bind_command! {
Math,
MathAbs,
MathAvg,
MathCeil,
MathEval,
MathFloor,
MathMax,
MathMedian,
MathMin,
MathMode,
MathProduct,
MathRound,
MathSqrt,
MathStddev,
MathSum,
MathVariance,
};
// Network
bind_command! {
Fetch,
Url,
UrlHost,
UrlPath,
UrlQuery,
UrlScheme,
}
// Random
bind_command! {
Random,
RandomBool,
RandomChars,
RandomDecimal,
RandomDice,
RandomInteger,
RandomUuid,
};
// Generators
bind_command! {
Cal,
Seq,
SeqDate,
};
// Hash
bind_command! {
Hash,
HashMd5::default(),
HashSha256::default(),
2022-01-22 17:23:55 +01:00
Base64,
};
2021-09-03 04:15:01 +02:00
2021-11-02 21:56:00 +01:00
#[cfg(feature = "plugin")]
bind_command!(Register);
// This is a WIP proof of concept
2021-11-26 09:00:57 +01:00
// bind_command!(ListGitBranches, Git, GitCheckout, Source);
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
}