0
# Command System
1
2
The Groovy Shell command system provides an extensible framework for implementing interactive shell commands. The system includes a command interface, registry management, and 15+ built-in commands for common shell operations.
3
4
## Capabilities
5
6
### Command Interface
7
8
Core interface that all shell commands must implement.
9
10
```groovy { .api }
11
/**
12
* Interface defining the contract for shell command implementations
13
*/
14
interface Command {
15
/** Get the command's canonical name */
16
String getName()
17
18
/** Get the command's shortcut (typically single character) */
19
String getShortcut()
20
21
/** Get tab completion support for this command */
22
Completer getCompleter()
23
24
/** Get brief description of the command */
25
String getDescription()
26
27
/** Get usage information showing command syntax */
28
String getUsage()
29
30
/** Get detailed help text explaining the command */
31
String getHelp()
32
33
/** Get list of command aliases */
34
List getAliases()
35
36
/** Execute the command with provided arguments */
37
Object execute(List<String> args)
38
39
/** Check if command should be hidden from help listings */
40
boolean getHidden()
41
}
42
```
43
44
### Command Support Base Class
45
46
Abstract base class providing common functionality for command implementations.
47
48
```groovy { .api }
49
/**
50
* Abstract base class providing common functionality for command implementations
51
*/
52
abstract class CommandSupport implements Command {
53
/** System line separator constant */
54
protected static final String NEWLINE = System.lineSeparator()
55
56
/** Command's canonical name */
57
final String name
58
59
/** Command's shortcut */
60
final String shortcut
61
62
/** List of command aliases */
63
final List aliases
64
65
/** Flag indicating if command is hidden from help */
66
boolean hidden
67
68
/**
69
* Create command with name and shortcut
70
* @param shell - The shell instance this command belongs to
71
* @param name - Command's canonical name
72
* @param shortcut - Command's shortcut
73
*/
74
CommandSupport(Groovysh shell, String name, String shortcut)
75
}
76
```
77
78
**Protected Methods** (available to subclasses):
79
80
```groovy { .api }
81
/** Override to provide custom tab completion */
82
List<Completer> createCompleters()
83
84
/** Create command alias */
85
void alias(String name, String shortcut)
86
87
/** Throw CommandException with message */
88
void fail(String msg)
89
90
/** Throw CommandException with cause */
91
void fail(String msg, Throwable cause)
92
93
/** Validate no arguments provided */
94
void assertNoArguments(List<String> args)
95
96
/** Access shell buffer manager */
97
BufferManager getBuffers()
98
99
/** Get current buffer */
100
List<String> getBuffer()
101
102
/** Get shell import statements */
103
List<String> getImports()
104
105
/** Get shell binding context */
106
Binding getBinding()
107
108
/** Get shell variables */
109
Map getVariables()
110
111
/** Get command history */
112
FileHistory getHistory()
113
114
/** Get shell class loader */
115
GroovyClassLoader getClassLoader()
116
```
117
118
**Usage Example:**
119
120
```groovy
121
import org.apache.groovy.groovysh.CommandSupport
122
123
class CustomCommand extends CommandSupport {
124
CustomCommand(shell) {
125
super(shell, ':custom', ':c')
126
this.description = 'Execute custom functionality'
127
}
128
129
Object execute(List<String> args) {
130
if (args.size() == 0) {
131
fail("Usage: :custom <argument>")
132
}
133
134
shell.io.out.println("Processing: ${args[0]}")
135
return "Custom result: ${args[0]}"
136
}
137
138
List<Completer> createCompleters() {
139
return [new SimpleCompleter('option1', 'option2', 'option3')]
140
}
141
}
142
143
// Register the command
144
shell.register(new CustomCommand(shell))
145
```
146
147
### Command Registry
148
149
Registry that manages available shell commands with name and shortcut uniqueness validation.
150
151
```groovy { .api }
152
/**
153
* Registry managing available shell commands with name/shortcut uniqueness
154
*/
155
class CommandRegistry {
156
/** List of registered commands */
157
final List<Command> commandList
158
159
/**
160
* Register a new command in the registry
161
* @param command - Command to register
162
* @return The registered command
163
* @throws AssertionError if name or shortcut conflicts
164
*/
165
Command register(Command command)
166
167
/**
168
* Find command by name or shortcut
169
* @param name - Command name or shortcut to search for
170
* @return Command instance or null if not found
171
*/
172
Command find(String name)
173
174
/**
175
* Remove command from registry
176
* @param command - Command to remove
177
*/
178
void remove(Command command)
179
180
/**
181
* Get all registered commands
182
* @return List of all commands
183
*/
184
List<Command> commands()
185
186
/**
187
* Property access for commands by name
188
* @param name - Command name
189
* @return Command instance
190
*/
191
Command getProperty(String name)
192
193
/**
194
* Iterator support for registry
195
* @return Iterator over commands
196
*/
197
Iterator iterator()
198
}
199
```
200
201
### Command Alias
202
203
Represents a command alias that delegates execution to another command.
204
205
```groovy { .api }
206
/**
207
* Command alias that delegates to another command
208
*/
209
class CommandAlias implements Command {
210
/** Target command this alias points to */
211
final Command target
212
213
/** Alias name */
214
final String name
215
216
/**
217
* Create command alias
218
* @param target - Command to alias
219
* @param name - Alias name
220
*/
221
CommandAlias(Command target, String name)
222
}
223
```
224
225
## Built-in Commands
226
227
The shell provides 15+ built-in commands organized by functionality:
228
229
### Core Commands
230
231
Essential shell operations and navigation.
232
233
```groovy { .api }
234
class HelpCommand extends CommandSupport {
235
public static final String COMMAND_NAME = ':help'
236
// Display help information for commands
237
}
238
239
class ExitCommand extends CommandSupport {
240
public static final String COMMAND_NAME = ':exit'
241
// Exit the shell with optional exit code
242
}
243
244
class ClearCommand extends CommandSupport {
245
public static final String COMMAND_NAME = ':clear'
246
// Clear current buffer contents
247
}
248
249
class DisplayCommand extends CommandSupport {
250
public static final String COMMAND_NAME = ':display'
251
// Display current buffer contents
252
}
253
254
class ShowCommand extends CommandSupport {
255
public static final String COMMAND_NAME = ':show'
256
// Show various shell information (variables, classes, imports, etc.)
257
}
258
```
259
260
### File Operations
261
262
Commands for loading, saving, and editing files.
263
264
```groovy { .api }
265
class LoadCommand extends CommandSupport {
266
public static final String COMMAND_NAME = ':load'
267
// Load and execute Groovy scripts from files
268
}
269
270
class SaveCommand extends CommandSupport {
271
public static final String COMMAND_NAME = ':save'
272
// Save current buffer contents to file
273
}
274
275
class EditCommand extends CommandSupport {
276
public static final String COMMAND_NAME = ':edit'
277
// Edit buffer contents with external editor
278
}
279
```
280
281
### Development Commands
282
283
Commands for code inspection, documentation, and dependency management.
284
285
```groovy { .api }
286
class InspectCommand extends CommandSupport {
287
public static final String COMMAND_NAME = ':inspect'
288
// Inspect objects and classes for methods and properties
289
}
290
291
class DocCommand extends CommandSupport {
292
public static final String COMMAND_NAME = ':doc'
293
// Show documentation for classes and methods
294
}
295
296
class ImportCommand extends CommandSupport {
297
public static final String COMMAND_NAME = ':import'
298
// Manage import statements
299
}
300
301
class GrabCommand extends CommandSupport {
302
public static final String COMMAND_NAME = ':grab'
303
// Download and add dependencies using Grape
304
}
305
```
306
307
### Utility Commands
308
309
Commands for shell configuration and session management.
310
311
```groovy { .api }
312
class HistoryCommand extends CommandSupport {
313
public static final String COMMAND_NAME = ':history'
314
// Manage and display command history
315
}
316
317
class AliasCommand extends CommandSupport {
318
public static final String COMMAND_NAME = ':alias'
319
// Create and manage command aliases
320
}
321
322
class SetCommand extends CommandSupport {
323
public static final String COMMAND_NAME = ':set'
324
// Configure shell settings and preferences
325
}
326
327
class RegisterCommand extends CommandSupport {
328
public static final String COMMAND_NAME = ':register'
329
// Register new commands from classes or scripts
330
}
331
332
class RecordCommand extends CommandSupport {
333
public static final String COMMAND_NAME = ':record'
334
// Record session activity to file
335
}
336
337
class PurgeCommand extends CommandSupport {
338
public static final String COMMAND_NAME = ':purge'
339
// Purge classes from memory to free up space
340
}
341
342
class ShadowCommand extends CommandSupport {
343
public static final String COMMAND_NAME = ':shadow'
344
// Create shadow copies of classes for testing
345
}
346
```
347
348
**Usage Examples:**
349
350
```groovy
351
// Load and execute a script
352
shell.execute(':load /path/to/script.groovy')
353
354
// Show all variables
355
shell.execute(':show variables')
356
357
// Inspect an object
358
shell.execute(':inspect myObject')
359
360
// Set shell preferences
361
shell.execute(':set interpreterMode true')
362
363
// Add import statement
364
shell.execute(':import java.util.concurrent.*')
365
366
// Display command history
367
shell.execute(':history show')
368
369
// Create command alias
370
shell.execute(':alias :q :exit')
371
```
372
373
### Command Registration Utilities
374
375
Helper classes for registering default and custom commands.
376
377
```groovy { .api }
378
/**
379
* Registers default shell commands
380
*/
381
class DefaultCommandsRegistrar {
382
/**
383
* Register all default commands with the shell
384
*/
385
void register()
386
387
/**
388
* Create registrar for shell
389
* @param shell - Shell instance to register commands with
390
*/
391
DefaultCommandsRegistrar(Groovysh shell)
392
}
393
394
/**
395
* Registers commands from XML configuration
396
*/
397
class XmlCommandRegistrar {
398
/**
399
* Register commands defined in XML resource
400
* @param xmlResource - URL to XML configuration file
401
*/
402
void register(URL xmlResource)
403
404
/**
405
* Create XML command registrar
406
* @param shell - Shell instance
407
* @param classLoader - ClassLoader for loading command classes
408
*/
409
XmlCommandRegistrar(Groovysh shell, ClassLoader classLoader)
410
}
411
```
412
413
## Exception Handling
414
415
```groovy { .api }
416
/**
417
* Exception thrown by command execution
418
*/
419
class CommandException extends Exception {
420
/** Command that threw the exception */
421
final Command command
422
423
/**
424
* Create command exception with message
425
* @param command - Command that failed
426
* @param message - Error message
427
*/
428
CommandException(Command command, String message)
429
430
/**
431
* Create command exception with cause
432
* @param command - Command that failed
433
* @param message - Error message
434
* @param cause - Underlying exception
435
*/
436
CommandException(Command command, String message, Throwable cause)
437
}
438
```
439
440
## Command Argument Processing
441
442
```groovy { .api }
443
/**
444
* Utility for parsing command line arguments
445
*/
446
class CommandArgumentParser {
447
/**
448
* Parse command line into arguments
449
* @param line - Command line string
450
* @return List of parsed arguments
451
*/
452
static List<String> parseLine(String line)
453
454
/**
455
* Parse command line with token limit
456
* @param line - Command line string
457
* @param maxTokens - Maximum number of tokens to parse
458
* @return List of parsed arguments
459
*/
460
static List<String> parseLine(String line, int maxTokens)
461
}
462
```
463
464
The command system provides a flexible framework for extending the shell with custom functionality while maintaining consistency in argument processing, error handling, and completion support.