Skip to main content

nu_command/
default_context.rs

1use crate::*;
2use nu_protocol::engine::{EngineState, StateWorkingSet};
3
4pub fn add_shell_command_context(mut engine_state: EngineState) -> EngineState {
5    let delta = {
6        let mut working_set = StateWorkingSet::new(&engine_state);
7
8        macro_rules! bind_command {
9            ( $( $command:expr ),* $(,)? ) => {
10                $( working_set.add_decl(Box::new($command)); )*
11            };
12        }
13
14        // If there are commands that have the same name as default declarations,
15        // they have to be registered before the main declarations. This helps to make
16        // them only accessible if the correct input value category is used with the
17        // declaration
18
19        // Database-related
20        // Adds all related commands to query databases
21        #[cfg(feature = "sqlite")]
22        add_database_decls(&mut working_set);
23
24        // Charts
25        bind_command! {
26            Histogram
27        }
28
29        // Filters
30        #[cfg(feature = "rand")]
31        bind_command! {
32            Shuffle
33        }
34        bind_command! {
35            All,
36            Any,
37            Append,
38            Chunks,
39            Columns,
40            Combinations,
41            Compact,
42            Default,
43            Difference,
44            Drop,
45            DropColumn,
46            DropNth,
47            Each,
48            Enumerate,
49            Every,
50            Filter,
51            Find,
52            First,
53            Flatten,
54            Get,
55            GroupBy,
56            Headers,
57            Insert,
58            IsEmpty,
59            IsNotEmpty,
60            Interleave,
61            Intersect,
62            Items,
63            Join,
64            Take,
65            Merge,
66            MergeDeep,
67            Move,
68            TakeWhile,
69            TakeUntil,
70            Last,
71            Length,
72            Lines,
73            ParEach,
74            Peek,
75            Permutations,
76            ChunkBy,
77            Prepend,
78            Reduce,
79            Reject,
80            Rename,
81            Reverse,
82            Select,
83            Skip,
84            SkipUntil,
85            SkipWhile,
86            Slice,
87            Sort,
88            SortBy,
89            SplitList,
90            Tee,
91            Transpose,
92            Uniq,
93            UniqBy,
94            Union,
95            Upsert,
96            Update,
97            Values,
98            Where,
99            Window,
100            Wrap,
101            Zip,
102        };
103
104        // Misc
105        bind_command! {
106            DeleteVar,
107            Panic,
108            Run,
109            Source,
110            Tutor,
111        };
112
113        // Path
114        bind_command! {
115            Path,
116            PathBasename,
117            PathSelf,
118            PathDirname,
119            PathExists,
120            PathExpand,
121            PathJoin,
122            PathParse,
123            PathRelativeTo,
124            PathSplit,
125            PathType,
126        };
127
128        // System
129        #[cfg(feature = "os")]
130        bind_command! {
131            Complete,
132            External,
133            Exec,
134            NuCheck,
135            RunInternal,
136            Sys,
137            SysCpu,
138            SysDisks,
139            SysHost,
140            SysMem,
141            SysNet,
142            SysTemp,
143            SysUsers,
144            UName,
145            Which,
146        };
147
148        // Help
149        bind_command! {
150            Help,
151            HelpAliases,
152            HelpExterns,
153            HelpCommands,
154            HelpModules,
155            HelpOperators,
156            HelpPipeAndRedirect,
157            HelpEscapes,
158        };
159
160        // Debug
161        bind_command! {
162            Ast,
163            Debug,
164            DebugEnv,
165            DebugExperimentalOptions,
166            DebugInfo,
167            DebugProfile,
168            Explain,
169            Inspect,
170            Metadata,
171            MetadataAccess,
172            MetadataSet,
173            TimeIt,
174            View,
175            ViewBlocks,
176            ViewFiles,
177            ViewIr,
178            ViewSource,
179            ViewSpan,
180        };
181
182        #[cfg(all(feature = "os", windows))]
183        bind_command! { Registry, RegistryQuery }
184
185        #[cfg(all(
186            feature = "os",
187            any(
188                target_os = "android",
189                target_os = "linux",
190                target_os = "freebsd",
191                target_os = "netbsd",
192                target_os = "openbsd",
193                target_os = "macos",
194                target_os = "windows"
195            )
196        ))]
197        bind_command! { Ps };
198
199        // Strings
200        bind_command! {
201            Ansi,
202            AnsiLink,
203            AnsiStrip,
204            Char,
205            Decode,
206            Encode,
207            DecodeHex,
208            EncodeHex,
209            DecodeBase32,
210            EncodeBase32,
211            DecodeBase32Hex,
212            EncodeBase32Hex,
213            DecodeBase64,
214            EncodeBase64,
215            Detect,
216            DetectColumns,
217            DetectType,
218            Parse,
219            Split,
220            SplitChars,
221            SplitColumn,
222            SplitRow,
223            SplitWords,
224            Str,
225            StrCapitalize,
226            StrContains,
227            StrDistance,
228            StrDowncase,
229            StrLowercase,
230            StrEndswith,
231            StrEscapeRegex,
232            StrExpand,
233            StrJoin,
234            StrReplace,
235            StrIndexOf,
236            StrLength,
237            StrReverse,
238            StrStats,
239            StrStartsWith,
240            StrSubstring,
241            StrTrim,
242            StrUpcase,
243            StrUppercase,
244            Format,
245            FormatDate,
246            FormatDuration,
247            FormatFilesize,
248        };
249
250        // FileSystem
251        #[cfg(feature = "os")]
252        bind_command! {
253            Cd,
254            Ls,
255            UMkdir,
256            Mktemp,
257            UMv,
258            UCp,
259            Open,
260            Start,
261            Rm,
262            Save,
263            UTouch,
264            Glob,
265            Watch,
266            Idx,
267            IdxInit,
268            IdxStatus,
269            IdxFind,
270            IdxSearch,
271            IdxWatch,
272            IdxDrop,
273            IdxDirs,
274            IdxFiles,
275        };
276
277        // Platform
278        #[cfg(all(feature = "os", not(target_arch = "wasm32")))]
279        if nu_experimental::NATIVE_CLIP.get() {
280            bind_command! {
281                ClipCommand,
282                ClipCopy,
283                ClipPaste,
284            };
285        }
286
287        #[cfg(feature = "os")]
288        bind_command! {
289            Clear,
290            Du,
291            Input,
292            InputList,
293            InputListen,
294            IsRedirected,
295            IsTerminal,
296            Kill,
297            Sleep,
298            Term,
299            TermSize,
300            TermQuery,
301            Whoami,
302        };
303
304        #[cfg(all(unix, feature = "os"))]
305        bind_command! { ULimit };
306
307        #[cfg(all(unix, feature = "os"))]
308        bind_command! { UMask };
309
310        // Date
311        bind_command! {
312            Date,
313            DateFromHuman,
314            DateHumanize,
315            DateListTimezones,
316            DateNow,
317            DateToTimezone,
318        };
319
320        // Shells
321        bind_command! {
322            Exit,
323        };
324
325        // Formats
326        bind_command! {
327            From,
328            FromCsv,
329            FromJson,
330            FromMd,
331            FromMsgpack,
332            FromMsgpackz,
333            FromNuon,
334            FromOds,
335            FromSsv,
336            FromToml,
337            FromTsv,
338            FromXlsx,
339            FromXml,
340            FROM_YAML,
341            FROM_YML,
342            FromKdl,
343            To,
344            ToCsv,
345            ToJson,
346            ToMd,
347            ToMsgpack,
348            ToMsgpackz,
349            ToNuon,
350            TO_TEXT,
351            TO_TXT,
352            ToToml,
353            ToTsv,
354            ToKdl,
355            Upsert,
356            Where,
357            ToXml,
358            TO_YAML,
359            TO_YML,
360        };
361
362        // Viewers
363        bind_command! {
364            Griddle,
365            Table,
366        };
367
368        // Conversions
369        bind_command! {
370            Fill,
371            Into,
372            IntoBool,
373            IntoBinary,
374            IntoCellPath,
375            IntoDatetime,
376            IntoDuration,
377            IntoFloat,
378            IntoFilesize,
379            IntoInt,
380            IntoMatrix,
381            IntoRecord,
382            IntoSemver,
383            IntoSemverRange,
384            IntoString,
385            IntoGlob,
386            IntoValue,
387            SplitCellPath,
388        };
389
390        // Semver
391        bind_command! {
392            Semver,
393            SemverBump,
394        };
395
396        // Matrix
397        bind_command! {
398            Matrix,
399            MatrixZeros,
400            MatrixIdentity,
401            MatrixGetRow,
402            MatrixGetCol,
403            MatrixSetRow,
404            MatrixSetCol,
405            MatrixAdd,
406            MatrixSubtract,
407            MatrixScale,
408            MatrixMultiply,
409            MatrixTranspose,
410            MatrixReshape,
411            MatrixMap,
412            MatrixReduce,
413            MatrixSum,
414            MatrixMean,
415            MatrixMax,
416            MatrixIntoNu,
417        };
418
419        // Env
420        bind_command! {
421            ExportEnv,
422            LoadEnv,
423            SourceEnv,
424            WithEnv,
425            ConfigNu,
426            ConfigEnv,
427            ConfigFlatten,
428            ConfigMeta,
429            ConfigReset,
430            ConfigUseColors,
431        };
432
433        // Math
434        bind_command! {
435            Math,
436            MathAbs,
437            MathAvg,
438            MathCbrt,
439            MathCeil,
440            MathFloor,
441            MathMax,
442            MathMedian,
443            MathMin,
444            MathMode,
445            MathProduct,
446            MathRound,
447            MathSqrt,
448            MathStddev,
449            MathSum,
450            MathVariance,
451            MathLog,
452        };
453
454        // Bytes
455        bind_command! {
456            Bytes,
457            BytesLen,
458            BytesSplit,
459            BytesStartsWith,
460            BytesEndsWith,
461            BytesReverse,
462            BytesReplace,
463            BytesAdd,
464            BytesAt,
465            BytesIndexOf,
466            BytesCollect,
467            BytesRemove,
468            BytesBuild
469        }
470
471        // Network
472        #[cfg(feature = "network")]
473        bind_command! {
474            Http,
475            HttpDelete,
476            HttpGet,
477            HttpHead,
478            HttpPatch,
479            HttpPost,
480            HttpPut,
481            HttpOptions,
482            HttpPool,
483            Port,
484            VersionCheck,
485        }
486        bind_command! {
487            Url,
488            UrlBuildQuery,
489            UrlSplitQuery,
490            UrlDecode,
491            UrlEncode,
492            UrlJoin,
493            UrlParse,
494        }
495
496        // Random
497        #[cfg(feature = "rand")]
498        bind_command! {
499            Random,
500            RandomBool,
501            RandomChars,
502            RandomFloat,
503            RandomInt,
504            RandomPass,
505            RandomUuid,
506            RandomBinary
507        };
508
509        // Generators
510        bind_command! {
511            Cal,
512            Seq,
513            SeqDate,
514            SeqChar,
515            Generate,
516        };
517
518        // Hash
519        bind_command! {
520            Hash,
521            HashMd5::default(),
522            HashSha256::default(),
523        };
524
525        // Experimental
526        bind_command! {
527            IsAdmin,
528            JobSpawn,
529            JobList,
530            JobKill,
531            JobId,
532            JobDescribe,
533            Job,
534        };
535
536        #[cfg(not(target_family = "wasm"))]
537        bind_command! {
538            JobSend,
539            JobRecv,
540            JobFlush,
541        }
542
543        #[cfg(all(unix, feature = "os"))]
544        bind_command! {
545            JobUnfreeze,
546        }
547
548        // Removed
549        bind_command! {
550            LetEnv,
551            DateFormat,
552        };
553
554        // Stor
555        #[cfg(feature = "sqlite")]
556        bind_command! {
557            Stor,
558            StorCreate,
559            StorDelete,
560            StorExport,
561            StorImport,
562            StorInsert,
563            StorOpen,
564            StorReset,
565            StorUpdate,
566        };
567
568        working_set.render()
569    };
570
571    if let Err(err) = engine_state.merge_delta(delta) {
572        eprintln!("Error creating default context: {err:?}");
573    }
574
575    // Cache the table decl id so we don't have to look it up later
576    let table_decl_id = engine_state.find_decl("table".as_bytes(), &[]);
577    engine_state.table_decl_id = table_decl_id;
578
579    engine_state
580}