Skip to main content

nu_protocol/engine/
command.rs

1use serde::{Deserialize, Serialize};
2
3use super::{EngineState, Stack, StateWorkingSet};
4use crate::{
5    Alias, BlockId, DeprecationEntry, DynamicCompletionCallRef, DynamicSuggestion, Example,
6    OutDest, PipelineData, ShellError, Signature, Span, Value, engine::Call,
7};
8use std::{
9    any::Any,
10    borrow::Cow,
11    fmt::{Debug, Display},
12};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum ArgType<'a> {
16    Flag(Cow<'a, str>),
17    Positional(usize),
18}
19
20impl<'a> Display for ArgType<'a> {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        match self {
23            ArgType::Flag(flag_name) => match flag_name {
24                Cow::Borrowed(v) => write!(f, "{v}"),
25                Cow::Owned(v) => write!(f, "{v}"),
26            },
27            ArgType::Positional(idx) => write!(f, "{idx}"),
28        }
29    }
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33pub enum CommandType {
34    Builtin,
35    Custom,
36    Keyword,
37    External,
38    Alias,
39    Plugin,
40}
41
42impl Display for CommandType {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        let str = match self {
45            CommandType::Builtin => "built-in",
46            CommandType::Custom => "custom",
47            CommandType::Keyword => "keyword",
48            CommandType::External => "external",
49            CommandType::Alias => "alias",
50            CommandType::Plugin => "plugin",
51        };
52        write!(f, "{str}")
53    }
54}
55
56pub trait Command: Send + Sync + CommandClone + Any {
57    fn name(&self) -> &str;
58
59    fn signature(&self) -> Signature;
60
61    /// Short preferably single sentence description for the command.
62    ///
63    /// Will be shown with the completions etc.
64    fn description(&self) -> &str;
65
66    /// Longer documentation description, if necessary.
67    ///
68    /// Will be shown below `description`
69    fn extra_description(&self) -> &str {
70        ""
71    }
72
73    fn run(
74        &self,
75        engine_state: &EngineState,
76        stack: &mut Stack,
77        call: &Call,
78        input: PipelineData,
79    ) -> Result<PipelineData, ShellError>;
80
81    /// Used by the parser to run command at parse time
82    ///
83    /// If a command has `is_const()` set to true, it must also implement this method.
84    #[allow(unused_variables)]
85    fn run_const(
86        &self,
87        working_set: &StateWorkingSet,
88        stack: &mut Stack,
89        call: &Call,
90        input: PipelineData,
91    ) -> Result<PipelineData, ShellError> {
92        Err(ShellError::MissingConstEvalImpl { span: call.head })
93    }
94
95    fn examples(&self) -> Vec<Example<'_>> {
96        Vec::new()
97    }
98
99    // Related terms to help with command search
100    fn search_terms(&self) -> Vec<&str> {
101        vec![]
102    }
103
104    fn attributes(&self) -> Vec<(String, Value)> {
105        vec![]
106    }
107
108    // Whether can run in const evaluation in the parser
109    fn is_const(&self) -> bool {
110        false
111    }
112
113    // Is a sub command
114    fn is_sub(&self) -> bool {
115        self.name().contains(' ')
116    }
117
118    // If command is a block i.e. def blah [] { }, get the block id
119    fn block_id(&self) -> Option<BlockId> {
120        None
121    }
122
123    // Return reference to the command as Alias
124    fn as_alias(&self) -> Option<&Alias> {
125        None
126    }
127
128    /// The identity of the plugin, if this is a plugin command
129    #[cfg(feature = "plugin")]
130    fn plugin_identity(&self) -> Option<&crate::PluginIdentity> {
131        None
132    }
133
134    fn command_type(&self) -> CommandType {
135        CommandType::Builtin
136    }
137
138    fn is_builtin(&self) -> bool {
139        self.command_type() == CommandType::Builtin
140    }
141
142    fn is_custom(&self) -> bool {
143        self.command_type() == CommandType::Custom
144    }
145
146    fn is_keyword(&self) -> bool {
147        self.command_type() == CommandType::Keyword
148    }
149
150    fn is_known_external(&self) -> bool {
151        self.command_type() == CommandType::External
152    }
153
154    /// The span of this command's declaration, if available.
155    /// Used to look up the source file where the command was declared.
156    /// Applicable to any command type that knows its declaration site.
157    fn decl_span(&self) -> Option<Span> {
158        None
159    }
160
161    fn is_alias(&self) -> bool {
162        self.command_type() == CommandType::Alias
163    }
164
165    fn is_plugin(&self) -> bool {
166        self.command_type() == CommandType::Plugin
167    }
168
169    fn deprecation_info(&self) -> Vec<DeprecationEntry> {
170        vec![]
171    }
172
173    fn pipe_redirection(&self) -> (Option<OutDest>, Option<OutDest>) {
174        (None, None)
175    }
176
177    // engine_state and stack are required to get completion from plugin.
178    /// Get completion items for `arg_type`.
179    ///
180    /// It's useful when you want to get auto completion items of a flag or positional argument
181    /// dynamically.
182    ///
183    /// The implementation can returns 3 types of return values:
184    /// - None: I couldn't find any suggestions, please fall back to default completions
185    /// - Some(vec![]): there are no suggestions
186    /// - Some(vec![item1, item2]): item1 and item2 are available
187    #[allow(unused_variables)]
188    #[expect(deprecated)]
189    fn get_dynamic_completion(
190        &self,
191        engine_state: &EngineState,
192        stack: &mut Stack,
193        call: DynamicCompletionCallRef,
194        arg_type: &ArgType,
195        _experimental: ExperimentalMarker,
196    ) -> Result<Option<Vec<DynamicSuggestion>>, ShellError> {
197        Ok(None)
198    }
199
200    /// Return true if the AST nodes for the arguments are required for IR evaluation. This is
201    /// currently inefficient so is not generally done.
202    fn requires_ast_for_arguments(&self) -> bool {
203        false
204    }
205}
206
207pub trait CommandClone {
208    fn clone_box(&self) -> Box<dyn Command>;
209}
210
211impl<T> CommandClone for T
212where
213    T: 'static + Command + Clone,
214{
215    fn clone_box(&self) -> Box<dyn Command> {
216        Box::new(self.clone())
217    }
218}
219
220impl Clone for Box<dyn Command> {
221    fn clone(&self) -> Box<dyn Command> {
222        self.clone_box()
223    }
224}
225
226/// Marker type for tagging [`Command`] methods as experimental.
227///
228/// Add this marker as a parameter to a method to make implementors see a deprecation warning when
229/// they implement it.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231#[deprecated(note = "this method is very experimental, likely to change")]
232pub struct ExperimentalMarker;