-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path250-cli.mdc
More file actions
383 lines (284 loc) · 7.59 KB
/
Copy path250-cli.mdc
File metadata and controls
383 lines (284 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
---
title: CLI Application Engineering Ruleset
description: Patterns and best practices for building command-line interfaces and tools.
priority: 250
alwaysApply: false
files:
include:
- "**/cmd/**/*.go"
- "**/cli/**/*.py"
- "**/cli/**/*.js"
- "**/bin/**/*"
- "**/*cli*.py"
- "**/*cli*.js"
- "**/main.go"
---
# CLI Application Engineering Ruleset
**Goal:** Build secure, user-friendly, debuggable command-line interfaces that follow platform conventions.
## Core Principles
- **User Experience First**: Clear error messages, helpful usage, intuitive flags
- **Debuggability**: Always provide debug mode for troubleshooting
- **Security**: Never log secrets, validate inputs, fail fast
- **Platform Conventions**: Follow platform-specific CLI patterns
## Debug Mode Patterns
### Environment Variable Pattern
```bash
# Enable debug mode
DEBUG=1 my-cli command
# Or with specific namespaces
DEBUG=my-cli:* my-cli command
```
### Command-Line Flag Pattern
```bash
# Enable debug mode
my-cli --debug command
# Verbose mode (different from debug)
my-cli --verbose command
# Quiet mode
my-cli --quiet command
```
### Implementation Examples
#### Python
```python
import os
import logging
import sys
# Setup logging
log_level = logging.INFO
if os.getenv("DEBUG") == "1" or "--debug" in sys.argv:
log_level = logging.DEBUG
logging.basicConfig(
level=log_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def main():
logger.debug("Debug mode enabled")
# ... rest of CLI logic
```
#### Node.js / JavaScript
Use the [`debug`](https://github.com/debug-js/debug) library:
```javascript
import debug from 'debug';
// Enable debug via environment variable
// DEBUG=1 npm start
// DEBUG=my-cli:* npm start
// DEBUG=my-cli:auth npm start
const debugLog = debug('my-cli:main');
const authDebug = debug('my-cli:auth');
function main() {
debugLog('Starting CLI application');
authDebug('Authenticating user');
// ... rest of CLI logic
}
// Enable debug output
if (process.env.DEBUG || process.env.AI_DEBUG_ENABLE === "1") {
debug.enabled = true;
}
```
#### Go
```go
package main
import (
"flag"
"log"
"os"
)
var (
debugFlag = flag.Bool("debug", false, "Enable debug logging")
verboseFlag = flag.Bool("verbose", false, "Enable verbose output")
)
func main() {
flag.Parse()
// Check environment variable
debugMode := *debugFlag || os.Getenv("DEBUG") == "1"
if debugMode {
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.SetOutput(os.Stderr)
}
log.Printf("Debug mode: %v", debugMode)
// ... rest of CLI logic
}
```
## CLI Structure Patterns
### Command Organization
```bash
# Top-level command with subcommands
my-cli init
my-cli deploy --env prod
my-cli status
my-cli logs --tail 100
# Or with explicit command structure
my-cli command subcommand --flags
```
### Flag Conventions
- Use `--long-flags` for readability
- Use `-s` for common short flags
- Group related flags
- Provide defaults and document them
```bash
# Good flag design
my-cli deploy \
--environment production \
--region us-east-1 \
--timeout 300 \
--dry-run
# Short flags for common options
my-cli deploy -e prod -r us-east-1 -t 300 --dry-run
```
## Error Handling
### Exit Codes
Follow Unix conventions:
- `0` - Success
- `1` - General error
- `2` - Misuse of shell command
- `126` - Command invoked cannot execute
- `127` - Command not found
- `128+n` - Fatal error signal "n"
### Error Messages
```python
# GOOD: Clear, actionable error message
if not config_file.exists():
print(f"Error: Configuration file not found: {config_file}", file=sys.stderr)
print(f"Hint: Run 'my-cli init' to create a default configuration", file=sys.stderr)
sys.exit(1)
# BAD: Vague error message
if not config_file.exists():
print("Error")
sys.exit(1)
```
### Structured Output
Support both human-readable and machine-readable output:
```bash
# Human-readable (default)
my-cli status
Status: Running
Version: 1.2.3
Uptime: 2h 15m
# Machine-readable (for scripting)
my-cli status --json
{"status":"running","version":"1.2.3","uptime":8100}
```
## Input Validation
### Validate Early, Fail Fast
```python
def deploy(environment: str, region: str):
# Validate inputs immediately
valid_environments = ["dev", "staging", "prod"]
if environment not in valid_environments:
print(f"Error: Invalid environment '{environment}'", file=sys.stderr)
print(f"Valid options: {', '.join(valid_environments)}", file=sys.stderr)
sys.exit(1)
valid_regions = ["us-east-1", "us-west-2", "eu-west-1"]
if region not in valid_regions:
print(f"Error: Invalid region '{region}'", file=sys.stderr)
sys.exit(1)
# Proceed with deployment
```
## Security Best Practices
### Never Log Secrets
```python
# GOOD: Mask secrets in logs
logger.debug(f"Connecting to API endpoint: {endpoint}")
logger.debug("Using API key: ***masked***")
# BAD: Logging secrets
logger.debug(f"API key: {api_key}")
```
### Input Sanitization
```python
import shlex
# GOOD: Sanitize shell commands
command = f"kubectl get pods -n {shlex.quote(namespace)}"
subprocess.run(command, shell=True)
# BAD: Unsanitized input
command = f"kubectl get pods -n {namespace}" # Vulnerable to injection
subprocess.run(command, shell=True)
```
### Credential Handling
```python
import getpass
# GOOD: Secure password input
password = getpass.getpass("Enter password: ")
# GOOD: Read from environment, not CLI args
api_key = os.getenv("API_KEY")
if not api_key:
print("Error: API_KEY environment variable not set", file=sys.stderr)
sys.exit(1)
```
## Progress Indicators
### Spinner for Long Operations
```python
import sys
import time
def show_spinner(message: str):
spinner = "|/-\\"
for i in range(20):
sys.stdout.write(f"\r{message} {spinner[i % len(spinner)]}")
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write("\r" + " " * (len(message) + 2) + "\r")
```
### Progress Bars
```python
from tqdm import tqdm
for item in tqdm(items, desc="Processing"):
process(item)
```
## Testing CLI Applications
### Test Exit Codes
```python
import subprocess
def test_cli_exit_code():
result = subprocess.run(
["my-cli", "invalid-command"],
capture_output=True
)
assert result.returncode == 1
assert "Error" in result.stderr.decode()
```
### Test Output
```python
def test_cli_output():
result = subprocess.run(
["my-cli", "status"],
capture_output=True,
text=True
)
assert result.returncode == 0
assert "Status: Running" in result.stdout
```
## Documentation
### Help Text
Always provide comprehensive help:
```bash
my-cli --help
my-cli command --help
my-cli command subcommand --help
```
### Man Pages
For complex CLIs, consider man pages:
```bash
man my-cli
man my-cli-deploy
```
## Platform-Specific Considerations
### Windows
- Use forward slashes or `os.path.join()`
- Handle line endings (`\r\n` vs `\n`)
- Consider PowerShell vs CMD differences
### macOS / Linux
- Follow Unix conventions
- Use `~` for home directory expansion
- Respect `$PATH` and environment variables
## Review Checklist
When reviewing CLI code, check:
- [ ] Debug mode implemented (environment variable or flag)
- [ ] Clear error messages with actionable hints
- [ ] Proper exit codes
- [ ] Input validation and sanitization
- [ ] No secrets in logs or output
- [ ] Help text is comprehensive
- [ ] Follows platform conventions
- [ ] Supports both human-readable and machine-readable output
- [ ] Progress indicators for long operations
---