nushell/crates/nu-command/src/default_context.rs
Taylor 494a5a5286
Add mktemp command (#11005)
closes #10845 

I've opened this a little prematurely to get some questions answered
before I cleanup the code.

As I started trying to better understand GNUs `mktemp` I've realized its
kind of peculiar and we might want to change its behavior to introduce
it to nushell.

#### quiet and dry run

Does it make sense to keep the `quiet` and `dry_run` flags? I don't
think so. The GNU documentation says this about the dry run flag "Using
the output of this command to create a new file is inherently unsafe, as
there is a window of time between generating the name and using it where
another process can create an object by the same name." So yeah why keep
it? As far as quiet goes, does it make sense to silence the errors in
nushell?

#### other confusing flags

According to the [gnu
docs](https://www.gnu.org/software/coreutils/manual/html_node/mktemp-invocation.html),
the `-t` flag is deprecated and the `-p`/ `--tempdir` are the same flag
with the only difference being `--tempdir` takes an optional path, Given
that, I've broken the `-p` away from `--tempdir`. Now there is one
switch `--tmpdir`/`-t` and one named param `--tmpdir-path`/`-p`.

GNU mktemp
```
  -p DIR, --tmpdir[=DIR]  interpret TEMPLATE relative to DIR; if DIR is not
                        specified, use $TMPDIR if set, else /tmp.  With
                        this option, TEMPLATE must not be an absolute name;
                        unlike with -t, TEMPLATE may contain slashes, but
                        mktemp creates only the final component
  -t                  interpret TEMPLATE as a single file name component,
                        relative to a directory: $TMPDIR, if set; else the
                        directory specified via -p; else /tmp [deprecated]

```
to
nushell mktemp
```
  -p, --tmpdir-path <Filepath> # named param, must provide a path
  -t, --tmpdir                 # a switch
```

Is this a terrible idea?

What should I do?

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2023-11-17 19:30:53 -06:00

419 lines
8.6 KiB
Rust

use nu_protocol::engine::{EngineState, StateWorkingSet};
use crate::{
help::{HelpAliases, HelpCommands, HelpEscapes, HelpExterns, HelpModules, HelpOperators},
*,
};
pub fn add_shell_command_context(mut engine_state: EngineState) -> EngineState {
let delta = {
let mut working_set = StateWorkingSet::new(&engine_state);
macro_rules! bind_command {
( $( $command:expr ),* $(,)? ) => {
$( working_set.add_decl(Box::new($command)); )*
};
}
// 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
// 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,
Default,
Drop,
DropColumn,
DropNth,
Each,
Empty,
Enumerate,
Every,
Filter,
Find,
First,
Flatten,
Get,
Group,
GroupBy,
Headers,
Insert,
Items,
Join,
SplitBy,
Take,
Merge,
Move,
TakeWhile,
TakeUntil,
Last,
Length,
Lines,
ParEach,
Prepend,
Range,
Reduce,
Reject,
Rename,
Reverse,
Select,
Shuffle,
Skip,
SkipUntil,
SkipWhile,
Sort,
SortBy,
SplitList,
Transpose,
Uniq,
UniqBy,
Upsert,
Update,
Values,
Where,
Window,
Wrap,
Zip,
};
// Misc
bind_command! {
Source,
Tutor,
};
// Path
bind_command! {
Path,
PathBasename,
PathDirname,
PathExists,
PathExpand,
PathJoin,
PathParse,
PathRelativeTo,
PathSplit,
PathType,
};
// System
bind_command! {
Complete,
External,
Exec,
NuCheck,
Sys,
};
// Help
bind_command! {
Help,
HelpAliases,
HelpExterns,
HelpCommands,
HelpModules,
HelpOperators,
HelpEscapes,
};
// Debug
bind_command! {
Ast,
Debug,
DebugInfo,
Explain,
Inspect,
Metadata,
TimeIt,
View,
ViewFiles,
ViewSource,
ViewSpan,
};
#[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,
DetectColumns,
Parse,
Split,
SplitChars,
SplitColumn,
SplitRow,
SplitWords,
Str,
StrCapitalize,
StrContains,
StrDistance,
StrDowncase,
StrEndswith,
StrExpand,
StrJoin,
StrReplace,
StrIndexOf,
StrLength,
StrReverse,
StrStats,
StrStartsWith,
StrSubstring,
StrTrim,
StrUpcase,
FormatDate,
FormatDuration,
FormatFilesize,
};
// FileSystem
bind_command! {
Cd,
Ls,
Mkdir,
UMkdir,
Mktemp,
Mv,
Cp,
UCp,
Open,
Start,
Rm,
Save,
Touch,
Glob,
Watch,
};
// Platform
bind_command! {
Ansi,
AnsiLink,
AnsiStrip,
Clear,
Du,
Input,
InputList,
InputListen,
Kill,
Sleep,
TermSize,
Whoami,
};
// Date
bind_command! {
Date,
DateHumanize,
DateListTimezones,
DateNow,
DateToRecord,
DateToTable,
DateToTimezone,
};
// Shells
bind_command! {
Exit,
};
// Formats
bind_command! {
From,
FromCsv,
FromJson,
FromNuon,
FromOds,
FromSsv,
FromToml,
FromTsv,
FromXlsx,
FromXml,
FromYaml,
FromYml,
To,
ToCsv,
ToJson,
ToMd,
ToNuon,
ToText,
ToToml,
ToTsv,
Touch,
Upsert,
Where,
ToXml,
ToYaml,
};
// Viewers
bind_command! {
Griddle,
Table,
};
// Conversions
bind_command! {
Fill,
Into,
IntoBool,
IntoBinary,
IntoDatetime,
IntoDuration,
IntoFloat,
IntoFilesize,
IntoInt,
IntoRecord,
IntoString,
IntoValue,
};
// Env
bind_command! {
ExportEnv,
LoadEnv,
SourceEnv,
WithEnv,
ConfigNu,
ConfigEnv,
ConfigMeta,
ConfigReset,
};
// Math
bind_command! {
Math,
MathAbs,
MathAvg,
MathCeil,
MathFloor,
MathMax,
MathMedian,
MathMin,
MathMode,
MathProduct,
MathRound,
MathSqrt,
MathStddev,
MathSum,
MathVariance,
MathLog,
};
// Bytes
bind_command! {
Bytes,
BytesLen,
BytesStartsWith,
BytesEndsWith,
BytesReverse,
BytesReplace,
BytesAdd,
BytesAt,
BytesIndexOf,
BytesCollect,
BytesRemove,
BytesBuild
}
// Network
bind_command! {
Http,
HttpDelete,
HttpGet,
HttpHead,
HttpPatch,
HttpPost,
HttpPut,
HttpOptions,
Url,
UrlBuildQuery,
UrlDecode,
UrlEncode,
UrlJoin,
UrlParse,
Port,
}
// Random
bind_command! {
Random,
RandomBool,
RandomChars,
RandomDice,
RandomFloat,
RandomInt,
RandomUuid,
};
// Generators
bind_command! {
Cal,
Seq,
SeqDate,
SeqChar,
Generate,
};
// Hash
bind_command! {
Hash,
HashMd5::default(),
HashSha256::default(),
};
// Experimental
bind_command! {
IsAdmin,
};
// Removed
bind_command! {
LetEnv,
DateFormat,
};
working_set.render()
};
if let Err(err) = engine_state.merge_delta(delta) {
eprintln!("Error creating default context: {err:?}");
}
// Cache the table decl id so we don't have to look it up later
let table_decl_id = engine_state.find_decl("table".as_bytes(), &[]);
engine_state.table_decl_id = table_decl_id;
engine_state
}