@nu-art/commando 0.401.0 → 0.401.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/{shell/core → core}/BaseCommando.d.ts +37 -6
  2. package/{shell/core → core}/BaseCommando.js +40 -6
  3. package/core/CliError.d.ts +49 -0
  4. package/core/CliError.js +58 -0
  5. package/{shell/core → core}/CommandBuilder.d.ts +27 -2
  6. package/{shell/core → core}/CommandBuilder.js +32 -3
  7. package/core/CommandoPool.d.ts +42 -0
  8. package/core/CommandoPool.js +48 -0
  9. package/core/class-merger.d.ts +39 -0
  10. package/core/class-merger.js +50 -0
  11. package/index.d.ts +11 -0
  12. package/index.js +16 -0
  13. package/{shell/interactive → interactive}/CommandoInteractive.d.ts +67 -7
  14. package/{shell/interactive → interactive}/CommandoInteractive.js +69 -6
  15. package/{shell/interactive → interactive}/InteractiveShell.d.ts +38 -0
  16. package/{shell/interactive → interactive}/InteractiveShell.js +25 -0
  17. package/package.json +24 -15
  18. package/plugins/basic.d.ts +140 -0
  19. package/plugins/basic.js +179 -0
  20. package/plugins/git.d.ts +169 -0
  21. package/plugins/git.js +219 -0
  22. package/plugins/nvm.d.ts +59 -0
  23. package/{shell/plugins → plugins}/nvm.js +47 -0
  24. package/plugins/pnpm.d.ts +42 -0
  25. package/{shell/plugins → plugins}/pnpm.js +31 -0
  26. package/{shell/plugins → plugins}/programming.d.ts +23 -3
  27. package/{shell/plugins → plugins}/programming.js +23 -3
  28. package/plugins/python.d.ts +41 -0
  29. package/plugins/python.js +58 -0
  30. package/services/nvm.d.ts +76 -0
  31. package/{shell/services → services}/nvm.js +67 -6
  32. package/services/pnpm.d.ts +67 -0
  33. package/{shell/services → services}/pnpm.js +41 -0
  34. package/simple/Commando.d.ts +92 -0
  35. package/simple/Commando.js +122 -0
  36. package/simple/SimpleShell.d.ts +48 -0
  37. package/{shell/simple → simple}/SimpleShell.js +32 -2
  38. package/tools.d.ts +33 -0
  39. package/tools.js +47 -0
  40. package/types.d.ts +17 -0
  41. package/cli-params/CLIParamsResolver.d.ts +0 -27
  42. package/cli-params/CLIParamsResolver.js +0 -97
  43. package/cli-params/consts.d.ts +0 -6
  44. package/cli-params/consts.js +0 -27
  45. package/cli-params/types.d.ts +0 -28
  46. package/shell/core/CliError.d.ts +0 -14
  47. package/shell/core/CliError.js +0 -23
  48. package/shell/core/CommandoPool.d.ts +0 -9
  49. package/shell/core/CommandoPool.js +0 -14
  50. package/shell/core/class-merger.d.ts +0 -20
  51. package/shell/core/class-merger.js +0 -35
  52. package/shell/index.d.ts +0 -2
  53. package/shell/index.js +0 -2
  54. package/shell/plugins/basic.d.ts +0 -59
  55. package/shell/plugins/basic.js +0 -98
  56. package/shell/plugins/git.d.ts +0 -54
  57. package/shell/plugins/git.js +0 -104
  58. package/shell/plugins/nvm.d.ts +0 -12
  59. package/shell/plugins/pnpm.d.ts +0 -11
  60. package/shell/plugins/python.d.ts +0 -10
  61. package/shell/plugins/python.js +0 -26
  62. package/shell/services/nvm.d.ts +0 -18
  63. package/shell/services/pnpm.d.ts +0 -26
  64. package/shell/simple/Commando.d.ts +0 -17
  65. package/shell/simple/Commando.js +0 -47
  66. package/shell/simple/SimpleShell.d.ts +0 -21
  67. package/shell/tools.d.ts +0 -3
  68. package/shell/tools.js +0 -17
  69. package/shell/types.d.ts +0 -3
  70. package/shell/types.js +0 -1
  71. /package/{cli-params/types.js → types.js} +0 -0
@@ -2,14 +2,39 @@ import { Constructor, LogLevel } from '@nu-art/ts-common';
2
2
  import { ShellLogProcessor, ShellPidListener } from './InteractiveShell.js';
3
3
  import { LogTypes } from '../types.js';
4
4
  import { BaseCommando } from '../core/BaseCommando.js';
5
+ /**
6
+ * Interactive shell command executor extending BaseCommando.
7
+ *
8
+ * Maintains a persistent bash session and executes commands in sequence,
9
+ * allowing state to persist between commands. Provides advanced features:
10
+ * - Log processing and filtering
11
+ * - Exit code extraction
12
+ * - Background process management
13
+ * - PID tracking for subprocesses
14
+ *
15
+ * **Key Differences from Commando**:
16
+ * - Uses InteractiveShell (persistent session) vs SimpleShell (one-shot)
17
+ * - Commands execute in the same shell context (variables persist)
18
+ * - Supports log processors for reactive command execution
19
+ * - Can run background processes and track their PIDs
20
+ *
21
+ * **Exit Code Extraction**:
22
+ * Uses a unique key pattern (`echo ${key}=$?`) to extract exit codes
23
+ * from both stdout and stderr, ensuring accurate exit code detection.
24
+ */
5
25
  export declare class CommandoInteractive extends BaseCommando {
26
+ /** Interactive shell instance managing the persistent session */
6
27
  private shell;
7
28
  /**
8
- * Creates a new instance of CommandoInteractive merged with the provided plugins.
9
- * @param {Constructor<any>[]} plugins - The plugins to merge with CommandoInteractive.
10
- * @returns {CommandoInteractive} - The new instance of CommandoInteractive merged with the plugins.
29
+ * Creates a CommandoInteractive instance with plugins.
30
+ *
31
+ * Initializes the InteractiveShell after merging plugins.
32
+ *
33
+ * @template T - Array of plugin constructor types
34
+ * @param plugins - Plugin classes to merge
35
+ * @returns Merged CommandoInteractive instance with plugins
11
36
  */
12
- static create<T extends Constructor<any>[]>(...plugins: T): import("../core/class-merger.js").MergeTypes<[typeof BaseCommando, typeof CommandoInteractive, ...T]> & BaseCommando & CommandoInteractive;
37
+ static create<T extends Constructor<any>[]>(...plugins: T): import("../index.js").MergeTypes<[typeof BaseCommando, typeof CommandoInteractive, ...T]> & BaseCommando & CommandoInteractive;
13
38
  /**
14
39
  * Constructs a CommandoInteractive instance.
15
40
  */
@@ -50,9 +75,27 @@ export declare class CommandoInteractive extends BaseCommando {
50
75
  */
51
76
  onLog(filter: string | RegExp, callback: (match: RegExpMatchArray) => any): this;
52
77
  /**
53
- * Executes commands and processes logs to extract exit code.
54
- * @param {Function} [callback] - A callback function to handle the command output.
55
- * @returns {Promise<T>} - The result of the callback function.
78
+ * Executes accumulated commands and extracts exit code from shell output.
79
+ *
80
+ * **Exit Code Extraction Strategy**:
81
+ * - Appends `echo ${uniqueKey}=$?` to both stdout and stderr
82
+ * - Uses log processors to detect the unique key pattern
83
+ * - Waits for both outputs (stdout and stderr) to capture exit code
84
+ * - Falls back to shell close event if pattern not detected
85
+ *
86
+ * **Log Processing**:
87
+ * - Adds temporary log processors to capture stdout/stderr
88
+ * - Accumulates all output until exit code is detected
89
+ * - Removes processors after execution (in finally block)
90
+ *
91
+ * **Behavior**:
92
+ * - Resolves when exit code is detected or shell closes
93
+ * - Calls callback with accumulated stdout, stderr, and exit code
94
+ * - Always cleans up log processors (even on error)
95
+ *
96
+ * @template T - Return type of callback
97
+ * @param callback - Function to process command output
98
+ * @returns Promise resolving to callback result
56
99
  */
57
100
  execute<T>(callback?: (stdout: string, stderr: string, exitCode: number) => T): Promise<T>;
58
101
  /**
@@ -75,6 +118,23 @@ export declare class CommandoInteractive extends BaseCommando {
75
118
  * @returns {this} - The CommandoInteractive instance for method chaining.
76
119
  */
77
120
  append(command: string): this;
121
+ mark(): this;
122
+ /**
123
+ * Appends a command to run in the background and tracks its PID.
124
+ *
125
+ * **Behavior**:
126
+ * - Runs command with `&` (background)
127
+ * - Captures PID using `pid=$!` and echoes it with unique key
128
+ * - Waits for the process to complete
129
+ * - Calls pidListener when PID is detected
130
+ *
131
+ * **Use Case**: Running long-running processes while continuing
132
+ * to execute other commands in the same shell session.
133
+ *
134
+ * @param command - Command to run in background
135
+ * @param pidListener - Optional callback when PID is detected
136
+ * @returns This instance for method chaining
137
+ */
78
138
  appendAsync(command: string, pidListener?: ShellPidListener): this;
79
139
  getCommand(): string;
80
140
  }
@@ -1,12 +1,37 @@
1
1
  import { generateHex } from '@nu-art/ts-common';
2
2
  import { InteractiveShell } from './InteractiveShell.js';
3
3
  import { BaseCommando } from '../core/BaseCommando.js';
4
+ /**
5
+ * Interactive shell command executor extending BaseCommando.
6
+ *
7
+ * Maintains a persistent bash session and executes commands in sequence,
8
+ * allowing state to persist between commands. Provides advanced features:
9
+ * - Log processing and filtering
10
+ * - Exit code extraction
11
+ * - Background process management
12
+ * - PID tracking for subprocesses
13
+ *
14
+ * **Key Differences from Commando**:
15
+ * - Uses InteractiveShell (persistent session) vs SimpleShell (one-shot)
16
+ * - Commands execute in the same shell context (variables persist)
17
+ * - Supports log processors for reactive command execution
18
+ * - Can run background processes and track their PIDs
19
+ *
20
+ * **Exit Code Extraction**:
21
+ * Uses a unique key pattern (`echo ${key}=$?`) to extract exit codes
22
+ * from both stdout and stderr, ensuring accurate exit code detection.
23
+ */
4
24
  export class CommandoInteractive extends BaseCommando {
25
+ /** Interactive shell instance managing the persistent session */
5
26
  shell;
6
27
  /**
7
- * Creates a new instance of CommandoInteractive merged with the provided plugins.
8
- * @param {Constructor<any>[]} plugins - The plugins to merge with CommandoInteractive.
9
- * @returns {CommandoInteractive} - The new instance of CommandoInteractive merged with the plugins.
28
+ * Creates a CommandoInteractive instance with plugins.
29
+ *
30
+ * Initializes the InteractiveShell after merging plugins.
31
+ *
32
+ * @template T - Array of plugin constructor types
33
+ * @param plugins - Plugin classes to merge
34
+ * @returns Merged CommandoInteractive instance with plugins
10
35
  */
11
36
  static create(...plugins) {
12
37
  const _commando = BaseCommando._create(CommandoInteractive, ...plugins);
@@ -80,9 +105,27 @@ export class CommandoInteractive extends BaseCommando {
80
105
  return this;
81
106
  }
82
107
  /**
83
- * Executes commands and processes logs to extract exit code.
84
- * @param {Function} [callback] - A callback function to handle the command output.
85
- * @returns {Promise<T>} - The result of the callback function.
108
+ * Executes accumulated commands and extracts exit code from shell output.
109
+ *
110
+ * **Exit Code Extraction Strategy**:
111
+ * - Appends `echo ${uniqueKey}=$?` to both stdout and stderr
112
+ * - Uses log processors to detect the unique key pattern
113
+ * - Waits for both outputs (stdout and stderr) to capture exit code
114
+ * - Falls back to shell close event if pattern not detected
115
+ *
116
+ * **Log Processing**:
117
+ * - Adds temporary log processors to capture stdout/stderr
118
+ * - Accumulates all output until exit code is detected
119
+ * - Removes processors after execution (in finally block)
120
+ *
121
+ * **Behavior**:
122
+ * - Resolves when exit code is detected or shell closes
123
+ * - Calls callback with accumulated stdout, stderr, and exit code
124
+ * - Always cleans up log processors (even on error)
125
+ *
126
+ * @template T - Return type of callback
127
+ * @param callback - Function to process command output
128
+ * @returns Promise resolving to callback result
86
129
  */
87
130
  async execute(callback) {
88
131
  let logProcessor;
@@ -171,6 +214,26 @@ export class CommandoInteractive extends BaseCommando {
171
214
  this.builder.append(command);
172
215
  return this;
173
216
  }
217
+ mark() {
218
+ this.builder.setMark();
219
+ return this;
220
+ }
221
+ /**
222
+ * Appends a command to run in the background and tracks its PID.
223
+ *
224
+ * **Behavior**:
225
+ * - Runs command with `&` (background)
226
+ * - Captures PID using `pid=$!` and echoes it with unique key
227
+ * - Waits for the process to complete
228
+ * - Calls pidListener when PID is detected
229
+ *
230
+ * **Use Case**: Running long-running processes while continuing
231
+ * to execute other commands in the same shell session.
232
+ *
233
+ * @param command - Command to run in background
234
+ * @param pidListener - Optional callback when PID is detected
235
+ * @returns This instance for method chaining
236
+ */
174
237
  appendAsync(command, pidListener) {
175
238
  const pidUniqueKey = generateHex(16);
176
239
  const regexp = new RegExp(`${pidUniqueKey}=(\\d+)`);
@@ -1,8 +1,46 @@
1
1
  import { Logger, LogLevel } from '@nu-art/ts-common';
2
2
  import { LogTypes } from '../types.js';
3
+ /**
4
+ * Function that processes log messages from shell output.
5
+ *
6
+ * Returns `false` to consume the log (prevent default logging),
7
+ * `true` to continue processing, or a Promise resolving to boolean.
8
+ *
9
+ * Processors are called in order until one returns `false`.
10
+ */
3
11
  export type ShellLogProcessor = (log: string, std: LogTypes) => (Promise<boolean> | boolean);
12
+ /**
13
+ * Function called when a subprocess PID is detected.
14
+ *
15
+ * Used with `appendAsync()` to notify when a background process starts.
16
+ */
4
17
  export type ShellPidListener = (pid: number) => (Promise<any> | any);
18
+ /**
19
+ * Listener called when the shell process closes.
20
+ */
5
21
  type OnCloseListener = (exitCode: number) => void;
22
+ /**
23
+ * Interactive shell session manager using Node.js child_process spawn.
24
+ *
25
+ * Maintains a persistent bash session and provides:
26
+ * - Command execution in the same shell context
27
+ * - Log processing pipeline (multiple processors)
28
+ * - Subprocess management (PID tracking, killing)
29
+ * - Exit code extraction via echo commands
30
+ *
31
+ * **Key Features**:
32
+ * - Detached process (session leader) for proper signal handling
33
+ * - Log processors can consume or pass through messages
34
+ * - Automatic log level filtering (stderr=Error, stdout=Info)
35
+ * - PID tracking for background processes
36
+ * - Graceful shutdown with timeout
37
+ *
38
+ * **Process Management**:
39
+ * - Spawns `/bin/bash` as detached process
40
+ * - Removes NODE_OPTIONS to prevent debug flags from propagating
41
+ * - Tracks process lifecycle (alive state)
42
+ * - Supports killing main shell or subprocesses independently
43
+ */
6
44
  export declare class InteractiveShell extends Logger {
7
45
  private _debug;
8
46
  private logProcessors;
@@ -1,6 +1,31 @@
1
1
  import { addItemToArrayAtIndex, currentTimeMillis, generateHex, Logger, LogLevel, removeItemFromArray } from '@nu-art/ts-common';
2
2
  import { spawn } from 'node:child_process';
3
+ /**
4
+ * Default log level filter: Error for stderr, Info for stdout.
5
+ */
3
6
  const defaultLogLevelFilter = (log, std) => std === 'err' ? LogLevel.Error : LogLevel.Info;
7
+ /**
8
+ * Interactive shell session manager using Node.js child_process spawn.
9
+ *
10
+ * Maintains a persistent bash session and provides:
11
+ * - Command execution in the same shell context
12
+ * - Log processing pipeline (multiple processors)
13
+ * - Subprocess management (PID tracking, killing)
14
+ * - Exit code extraction via echo commands
15
+ *
16
+ * **Key Features**:
17
+ * - Detached process (session leader) for proper signal handling
18
+ * - Log processors can consume or pass through messages
19
+ * - Automatic log level filtering (stderr=Error, stdout=Info)
20
+ * - PID tracking for background processes
21
+ * - Graceful shutdown with timeout
22
+ *
23
+ * **Process Management**:
24
+ * - Spawns `/bin/bash` as detached process
25
+ * - Removes NODE_OPTIONS to prevent debug flags from propagating
26
+ * - Tracks process lifecycle (alive state)
27
+ * - Supports killing main shell or subprocesses independently
28
+ */
4
29
  export class InteractiveShell extends Logger {
5
30
  _debug = false;
6
31
  logProcessors = [];
package/package.json CHANGED
@@ -1,24 +1,33 @@
1
1
  {
2
2
  "name": "@nu-art/commando",
3
- "version": "0.401.0",
4
- "description": "",
3
+ "version": "0.401.2",
4
+ "description": "Shell command execution framework with interactive sessions, CLI parameter resolution, and plugin system for building and executing shell scripts programmatically",
5
5
  "type": "module",
6
6
  "keywords": [
7
- "TacB0sS",
8
- "infra",
7
+ "shell",
8
+ "command-execution",
9
+ "cli",
10
+ "bash",
11
+ "interactive-shell",
12
+ "shell-scripts",
13
+ "cli-params",
14
+ "command-line",
9
15
  "nu-art",
10
- "commando"
16
+ "thunderstorm",
17
+ "commando",
18
+ "typescript"
11
19
  ],
12
20
  "homepage": "https://github.com/nu-art-js/thunderstorm",
13
21
  "bugs": {
14
- "url": "https://github.com/nu-art-js/thunderstorm/issues"
15
- },
16
- "publishConfig": {
17
- "directory": "dist"
22
+ "url": "https://github.com/nu-art-js/thunderstorm/issues?q=is%3Aissue+label%3Acommando"
18
23
  },
19
24
  "repository": {
20
25
  "type": "git",
21
- "url": "git+ssh://git@github.com:nu-art-js/thunderstorm.git"
26
+ "url": "git+ssh://git@github.com:nu-art-js/thunderstorm.git",
27
+ "directory": "_thunderstorm/commando"
28
+ },
29
+ "publishConfig": {
30
+ "directory": "dist"
22
31
  },
23
32
  "license": "Apache-2.0",
24
33
  "author": "TacB0sS",
@@ -29,7 +38,11 @@
29
38
  "build": "tsc"
30
39
  },
31
40
  "dependencies": {
32
- "@nu-art/ts-common": "0.401.0"
41
+ "@nu-art/cli-params": "0.401.2",
42
+ "@nu-art/ts-common": "0.401.2"
43
+ },
44
+ "devDependencies": {
45
+ "@nu-art/testalot": "0.401.2"
33
46
  },
34
47
  "unitConfig": {
35
48
  "type": "typescript-lib"
@@ -38,10 +51,6 @@
38
51
  ".": {
39
52
  "types": "./index.d.ts",
40
53
  "import": "./index.js"
41
- },
42
- "./*": {
43
- "types": "./*.d.ts",
44
- "import": "./*.js"
45
54
  }
46
55
  }
47
56
  }
@@ -0,0 +1,140 @@
1
+ import { BaseCommando } from '../core/BaseCommando.js';
2
+ import { CliBlock } from '../types.js';
3
+ type Cli_EchoOptions = {
4
+ escape?: boolean;
5
+ toFile?: {
6
+ name: string;
7
+ append?: boolean;
8
+ };
9
+ };
10
+ type Cli_RmdirOptions = {
11
+ force?: true;
12
+ recursive?: true;
13
+ };
14
+ type Cli_CpdirOptions = {
15
+ contentOnly?: boolean;
16
+ };
17
+ /**
18
+ * Basic shell command plugin for Commando.
19
+ *
20
+ * Provides common file system and shell operations:
21
+ * - Directory navigation (`cd`, `pwd`)
22
+ * - File operations (`ls`, `cat`, `mkdir`, `rm`, `rmdir`, `cpdir`)
23
+ * - Variable assignment
24
+ * - Echo with options (escape sequences, file output)
25
+ *
26
+ * **Usage**: Merge with BaseCommando or other Commando classes to add
27
+ * these methods. Typically included via `CommandoPool.allocateCommando()`.
28
+ */
29
+ export declare class Commando_Basic extends BaseCommando {
30
+ /**
31
+ * Changes directory and optionally executes commands in that directory.
32
+ *
33
+ * **Behavior**:
34
+ * - Changes to the specified directory
35
+ * - Increases indentation (for script readability)
36
+ * - If `toRun` provided, executes the block and returns to previous directory
37
+ * - If `toRun` not provided, caller must call `cd_()` to return
38
+ *
39
+ * **Note**: Uses `cd -` to return to previous directory (OLDPWD).
40
+ *
41
+ * @param folderName - Directory path to change to
42
+ * @param toRun - Optional command block to execute in the directory
43
+ * @returns This instance for method chaining
44
+ */
45
+ cd(folderName: string, toRun?: CliBlock<this>): this;
46
+ /**
47
+ * Appends a custom command string.
48
+ *
49
+ * Allows adding arbitrary shell commands that aren't covered by
50
+ * the built-in methods.
51
+ *
52
+ * @param command - Custom shell command to append
53
+ * @returns This instance for method chaining
54
+ */
55
+ custom(command: string): this;
56
+ /**
57
+ * Changes directory back to the previous directory.
58
+ * @returns {this} - The Cli instance for method chaining.
59
+ */
60
+ cd_(): this;
61
+ /**
62
+ * Appends an 'ls' command with optional parameters.
63
+ * @param {string} [params] - Optional parameters for the 'ls' command.
64
+ * @returns {this} - The Cli instance for method chaining.
65
+ */
66
+ ls(params?: string): this;
67
+ /**
68
+ * Creates a directory (with parent directories if needed).
69
+ *
70
+ * Uses `mkdir -p` to create directory and all parent directories.
71
+ *
72
+ * @param dirName - Directory path to create
73
+ * @returns This instance for method chaining
74
+ */
75
+ mkdir(dirName: string): this;
76
+ /**
77
+ * Removes a file or directory.
78
+ *
79
+ * @param dirPath - Path to remove
80
+ * @param options - Optional force flag
81
+ * @returns This instance for method chaining
82
+ */
83
+ rm(dirPath: string, options?: Cli_RmdirOptions): this;
84
+ /**
85
+ * Removes a directory recursively.
86
+ *
87
+ * @param dirPath - Directory path to remove
88
+ * @param options - Optional force flag
89
+ * @returns This instance for method chaining
90
+ */
91
+ rmdir(dirPath: string, options?: Cli_RmdirOptions): this;
92
+ /**
93
+ * Copies a directory.
94
+ *
95
+ * @param srcPath - Source directory path
96
+ * @param destPath - Destination directory path
97
+ * @param options - Optional contentOnly flag (copies contents, not directory itself)
98
+ * @returns This instance for method chaining
99
+ */
100
+ cpdir(srcPath: string, destPath: string, options?: Cli_CpdirOptions): this;
101
+ /**
102
+ * Displays file contents.
103
+ *
104
+ * @param fileName - File path to display
105
+ * @returns This instance for method chaining
106
+ */
107
+ cat(fileName: string): this;
108
+ /**
109
+ * Echoes text with optional escape sequences and file output.
110
+ *
111
+ * **Escape Sequences**: When `escape` is true, enables interpretation
112
+ * of backslash escapes (e.g., `\n`, `\t`).
113
+ *
114
+ * **File Output**: Can append or overwrite to a file.
115
+ *
116
+ * **Escaping**: Automatically escapes backslashes, newlines, and tabs
117
+ * in the log string for safe shell execution.
118
+ *
119
+ * @param log - Text to echo
120
+ * @param options - Optional echo configuration
121
+ * @returns This instance for method chaining
122
+ */
123
+ echo(log: string, options?: Cli_EchoOptions): this;
124
+ /**
125
+ * Appends a 'pwd' command to print the current directory.
126
+ * @returns {this} - The Cli instance for method chaining.
127
+ */
128
+ pwd(): this;
129
+ /**
130
+ * Assigns a value to a shell variable (array or scalar).
131
+ *
132
+ * Creates a bash array if value is an array, otherwise creates a scalar variable.
133
+ *
134
+ * @param varName - Variable name
135
+ * @param value - Value(s) to assign (string or array of strings)
136
+ * @returns This instance for method chaining
137
+ */
138
+ assignVar(varName: string, value: string | string[]): this;
139
+ }
140
+ export {};
@@ -0,0 +1,179 @@
1
+ import { BaseCommando } from '../core/BaseCommando.js';
2
+ /**
3
+ * Basic shell command plugin for Commando.
4
+ *
5
+ * Provides common file system and shell operations:
6
+ * - Directory navigation (`cd`, `pwd`)
7
+ * - File operations (`ls`, `cat`, `mkdir`, `rm`, `rmdir`, `cpdir`)
8
+ * - Variable assignment
9
+ * - Echo with options (escape sequences, file output)
10
+ *
11
+ * **Usage**: Merge with BaseCommando or other Commando classes to add
12
+ * these methods. Typically included via `CommandoPool.allocateCommando()`.
13
+ */
14
+ export class Commando_Basic extends BaseCommando {
15
+ /**
16
+ * Changes directory and optionally executes commands in that directory.
17
+ *
18
+ * **Behavior**:
19
+ * - Changes to the specified directory
20
+ * - Increases indentation (for script readability)
21
+ * - If `toRun` provided, executes the block and returns to previous directory
22
+ * - If `toRun` not provided, caller must call `cd_()` to return
23
+ *
24
+ * **Note**: Uses `cd -` to return to previous directory (OLDPWD).
25
+ *
26
+ * @param folderName - Directory path to change to
27
+ * @param toRun - Optional command block to execute in the directory
28
+ * @returns This instance for method chaining
29
+ */
30
+ cd(folderName, toRun) {
31
+ this.append(`cd ${folderName}`);
32
+ this.indentIn();
33
+ if (toRun) {
34
+ toRun(this);
35
+ this.cd_();
36
+ }
37
+ return this;
38
+ }
39
+ /**
40
+ * Appends a custom command string.
41
+ *
42
+ * Allows adding arbitrary shell commands that aren't covered by
43
+ * the built-in methods.
44
+ *
45
+ * @param command - Custom shell command to append
46
+ * @returns This instance for method chaining
47
+ */
48
+ custom(command) {
49
+ this.append(command);
50
+ return this;
51
+ }
52
+ /**
53
+ * Changes directory back to the previous directory.
54
+ * @returns {this} - The Cli instance for method chaining.
55
+ */
56
+ cd_() {
57
+ this.indentOut();
58
+ this.append(`cd -`);
59
+ return this;
60
+ }
61
+ /**
62
+ * Appends an 'ls' command with optional parameters.
63
+ * @param {string} [params] - Optional parameters for the 'ls' command.
64
+ * @returns {this} - The Cli instance for method chaining.
65
+ */
66
+ ls(params = '') {
67
+ this.append(`ls ${params}`);
68
+ return this;
69
+ }
70
+ /**
71
+ * Creates a directory (with parent directories if needed).
72
+ *
73
+ * Uses `mkdir -p` to create directory and all parent directories.
74
+ *
75
+ * @param dirName - Directory path to create
76
+ * @returns This instance for method chaining
77
+ */
78
+ mkdir(dirName) {
79
+ this.append(`mkdir -p ${dirName}`);
80
+ return this;
81
+ }
82
+ /**
83
+ * Removes a file or directory.
84
+ *
85
+ * @param dirPath - Path to remove
86
+ * @param options - Optional force flag
87
+ * @returns This instance for method chaining
88
+ */
89
+ rm(dirPath, options) {
90
+ let command = 'rm';
91
+ if (options?.force)
92
+ command += ' -f';
93
+ this.append(`${command} ${dirPath}`);
94
+ return this;
95
+ }
96
+ /**
97
+ * Removes a directory recursively.
98
+ *
99
+ * @param dirPath - Directory path to remove
100
+ * @param options - Optional force flag
101
+ * @returns This instance for method chaining
102
+ */
103
+ rmdir(dirPath, options) {
104
+ let command = 'rm -r';
105
+ if (options?.force)
106
+ command += ' -f';
107
+ this.append(`${command} ${dirPath}`);
108
+ return this;
109
+ }
110
+ /**
111
+ * Copies a directory.
112
+ *
113
+ * @param srcPath - Source directory path
114
+ * @param destPath - Destination directory path
115
+ * @param options - Optional contentOnly flag (copies contents, not directory itself)
116
+ * @returns This instance for method chaining
117
+ */
118
+ cpdir(srcPath, destPath, options) {
119
+ let command = `cp -r ${srcPath}`;
120
+ if (options?.contentOnly)
121
+ command += '/*';
122
+ command += ` ${destPath}`;
123
+ this.append(command);
124
+ return this;
125
+ }
126
+ /**
127
+ * Displays file contents.
128
+ *
129
+ * @param fileName - File path to display
130
+ * @returns This instance for method chaining
131
+ */
132
+ cat(fileName) {
133
+ this.append(`cat ${fileName}`);
134
+ return this;
135
+ }
136
+ /**
137
+ * Echoes text with optional escape sequences and file output.
138
+ *
139
+ * **Escape Sequences**: When `escape` is true, enables interpretation
140
+ * of backslash escapes (e.g., `\n`, `\t`).
141
+ *
142
+ * **File Output**: Can append or overwrite to a file.
143
+ *
144
+ * **Escaping**: Automatically escapes backslashes, newlines, and tabs
145
+ * in the log string for safe shell execution.
146
+ *
147
+ * @param log - Text to echo
148
+ * @param options - Optional echo configuration
149
+ * @returns This instance for method chaining
150
+ */
151
+ echo(log, options) {
152
+ const _escape = options?.escape ? '-e' : '';
153
+ const _toFile = options?.toFile ? `>${options.toFile.append ? '>' : ''} ${options.toFile.name}` : '';
154
+ const escapedLog = log.replace(/\\/g, '\\\\').replace(/\n/g, '\\\\n').replace(/\t/g, '\\\t');
155
+ this.append(`echo ${_escape} "${escapedLog}" ${_toFile}`);
156
+ return this;
157
+ }
158
+ /**
159
+ * Appends a 'pwd' command to print the current directory.
160
+ * @returns {this} - The Cli instance for method chaining.
161
+ */
162
+ pwd() {
163
+ this.append('pwd');
164
+ return this;
165
+ }
166
+ /**
167
+ * Assigns a value to a shell variable (array or scalar).
168
+ *
169
+ * Creates a bash array if value is an array, otherwise creates a scalar variable.
170
+ *
171
+ * @param varName - Variable name
172
+ * @param value - Value(s) to assign (string or array of strings)
173
+ * @returns This instance for method chaining
174
+ */
175
+ assignVar(varName, value) {
176
+ this.append(`${varName}=(${Array.isArray(value) ? value : [value].join(' ')})`);
177
+ return this;
178
+ }
179
+ }