nushell/crates/nu-command/src/default_context.rs
Darren Schroeder cdbb3ee7b9
add version check command (#14880)
# Description

This PR supersedes https://github.com/nushell/nushell/pull/14813 by
making it a built-in command instead of checking for the latest version
at some interval when nushell starts.

This is what it looks like.

![image](https://github.com/user-attachments/assets/35629425-b332-4078-aea5-4931cfb0471f)

This example shows the output when the running version was
0.101.1-nightly.10

![image](https://github.com/user-attachments/assets/71216635-fb75-4251-a443-bf0d0b9a1c07)


Description from old PR.
One key functionality that I thought was interesting with this and that
I worked with @hustcer on was to try and make sure it works with
nightlies. So, it should tell you when there's a new nightly version
that is available to download. This way, you can know about it without
checking.

What's key from a nightly perspective is (1) the tags are now semver
compliant and (2) hustcer now updates the Cargo.toml package.version
version number prior to compilation so you can know you're running a
nightly version, and this PR uses that information to know whether to
check the nightly repo or the nushell repo for updates.

This uses the
[update-informer](https://docs.rs/update-informer/latest/update_informer/)
crate. NOTE that this _informs_ you of updates but does not
automatically update. I kind of see this as the first step to eventually
having an auto updater.

There was caching of the version in the old PR since it ran on every
nushell startup. Since this PR makes it a command and therefore always
runs on-demand, I've removed the caching so that it always checks when
you run it.

# 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` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# 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.
-->
2025-01-23 15:23:17 +01:00

486 lines
10 KiB
Rust

use crate::*;
use nu_protocol::engine::{EngineState, StateWorkingSet};
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
#[cfg(feature = "rand")]
bind_command! {
Shuffle
}
bind_command! {
All,
Any,
Append,
Chunks,
Columns,
Compact,
Default,
Drop,
DropColumn,
DropNth,
Each,
Enumerate,
Every,
Filter,
Find,
First,
Flatten,
Get,
GroupBy,
Headers,
Insert,
IsEmpty,
IsNotEmpty,
Interleave,
Items,
Join,
Take,
Merge,
MergeDeep,
Move,
TakeWhile,
TakeUntil,
Last,
Length,
Lines,
ParEach,
ChunkBy,
Prepend,
Range,
Reduce,
Reject,
Rename,
Reverse,
Select,
Skip,
SkipUntil,
SkipWhile,
Slice,
Sort,
SortBy,
SplitList,
Tee,
Transpose,
Uniq,
UniqBy,
Upsert,
Update,
Values,
Where,
Window,
Wrap,
Zip,
};
// Misc
bind_command! {
Panic,
Source,
Tutor,
};
// Path
bind_command! {
Path,
PathBasename,
PathSelf,
PathDirname,
PathExists,
PathExpand,
PathJoin,
PathParse,
PathRelativeTo,
PathSplit,
PathType,
};
// System
#[cfg(feature = "os")]
bind_command! {
Complete,
External,
Exec,
NuCheck,
Sys,
SysCpu,
SysDisks,
SysHost,
SysMem,
SysNet,
SysTemp,
SysUsers,
UName,
Which,
};
// Help
bind_command! {
Help,
HelpAliases,
HelpExterns,
HelpCommands,
HelpModules,
HelpOperators,
HelpPipeAndRedirect,
HelpEscapes,
};
// Debug
bind_command! {
Ast,
Debug,
DebugInfo,
DebugProfile,
Explain,
Inspect,
Metadata,
MetadataAccess,
MetadataSet,
TimeIt,
View,
ViewBlocks,
ViewFiles,
ViewIr,
ViewSource,
ViewSpan,
};
#[cfg(all(feature = "os", windows))]
bind_command! { RegistryQuery }
#[cfg(all(
feature = "os",
any(
target_os = "android",
target_os = "linux",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "macos",
target_os = "windows"
)
))]
bind_command! { Ps };
// Strings
bind_command! {
Char,
Decode,
Encode,
DecodeHex,
EncodeHex,
DecodeBase32,
EncodeBase32,
DecodeBase32Hex,
EncodeBase32Hex,
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,
Format,
FormatDate,
FormatDuration,
FormatFilesize,
};
// FileSystem
#[cfg(feature = "os")]
bind_command! {
Cd,
Ls,
UMkdir,
Mktemp,
UMv,
UCp,
Open,
Start,
Rm,
Save,
UTouch,
Glob,
Watch,
};
// Platform
#[cfg(feature = "os")]
bind_command! {
Ansi,
AnsiLink,
AnsiStrip,
Clear,
Du,
Input,
InputList,
InputListen,
IsTerminal,
Kill,
Sleep,
Term,
TermSize,
TermQuery,
Whoami,
};
#[cfg(all(unix, feature = "os"))]
bind_command! { ULimit };
// Date
bind_command! {
Date,
DateHumanize,
DateListTimezones,
DateNow,
DateToTimezone,
};
// Shells
bind_command! {
Exit,
};
// Formats
bind_command! {
From,
FromCsv,
FromJson,
FromMsgpack,
FromMsgpackz,
FromNuon,
FromOds,
FromSsv,
FromToml,
FromTsv,
FromXlsx,
FromXml,
FromYaml,
FromYml,
To,
ToCsv,
ToJson,
ToMd,
ToMsgpack,
ToMsgpackz,
ToNuon,
ToText,
ToToml,
ToTsv,
Upsert,
Where,
ToXml,
ToYaml,
};
// Viewers
bind_command! {
Griddle,
Table,
};
// Conversions
bind_command! {
Fill,
Into,
IntoBool,
IntoBinary,
IntoCellPath,
IntoDatetime,
IntoDuration,
IntoFloat,
IntoFilesize,
IntoInt,
IntoRecord,
IntoString,
IntoGlob,
IntoValue,
SplitCellPath,
};
// Env
bind_command! {
ExportEnv,
LoadEnv,
SourceEnv,
WithEnv,
ConfigNu,
ConfigEnv,
ConfigFlatten,
ConfigMeta,
ConfigReset,
ConfigUseColors,
};
// Math
bind_command! {
Math,
MathAbs,
MathAvg,
MathCeil,
MathFloor,
MathMax,
MathMedian,
MathMin,
MathMode,
MathProduct,
MathRound,
MathSqrt,
MathStddev,
MathSum,
MathVariance,
MathLog,
};
// Bytes
bind_command! {
Bytes,
BytesLen,
BytesSplit,
BytesStartsWith,
BytesEndsWith,
BytesReverse,
BytesReplace,
BytesAdd,
BytesAt,
BytesIndexOf,
BytesCollect,
BytesRemove,
BytesBuild
}
// Network
#[cfg(feature = "network")]
bind_command! {
Http,
HttpDelete,
HttpGet,
HttpHead,
HttpPatch,
HttpPost,
HttpPut,
HttpOptions,
Port,
VersionCheck,
}
bind_command! {
Url,
UrlBuildQuery,
UrlSplitQuery,
UrlDecode,
UrlEncode,
UrlJoin,
UrlParse,
}
// Random
#[cfg(feature = "rand")]
bind_command! {
Random,
RandomBool,
RandomChars,
RandomDice,
RandomFloat,
RandomInt,
RandomUuid,
RandomBinary
};
// 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,
};
// Stor
#[cfg(feature = "sqlite")]
bind_command! {
Stor,
StorCreate,
StorDelete,
StorExport,
StorImport,
StorInsert,
StorOpen,
StorReset,
StorUpdate,
};
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
}