Gluegun CLI Toolkit Patterns
Provides comprehensive patterns and templates for building TypeScript-powered CLI applications using the Gluegun toolkit. Gluegun offers parameters, templates, filesystem operations, HTTP utilities, prompts, and extensible plugin architecture.
Core Capabilities
Gluegun provides these essential toolbox features:
- Parameters - Command-line arguments and options parsing
- Template - EJS-based file generation from templates
- Filesystem - File and directory operations (fs-jetpack)
- System - Execute external commands and scripts
- HTTP - API interactions with axios/apisauce
- Prompt - Interactive user input with enquirer
- Print - Colorful console output with colors/ora
- Patching - Modify existing file contents
- Semver - Version string manipulation
- Plugin System - Extensible command architecture
Instructions
Building a Basic CLI
Initialize Gluegun CLI structure:
import { build } from 'gluegun'
const cli = build()
.brand('mycli')
.src(__dirname)
.plugins('./node_modules', { matching: 'mycli-*', hidden: true })
.help()
.version()
.create()
Create command structure:
- Commands go in
src/commands/ directory
- Each command exports a
GluegunCommand object
- Use templates from
templates/ directory
- Reference template:
templates/commands/basic-command.ts.ejs
Implement command with toolbox:
module.exports = {
name: 'generate',
run: async (toolbox) => {
const { template, print, parameters } = toolbox
const name = parameters.first
await template.generate({
template: 'model.ts.ejs',
target: `src/models/${name}.ts`,
props: { name }
})
print.success(`Generated ${name} model`)
}
}
Template System
Template file structure:
- Store templates in
templates/ directory
- Use EJS syntax:
<%= variable %>, <%- unescaped %>
- Reference:
templates/toolbox/template-examples.ejs
Generate files from templates:
await template.generate({
template: 'component.tsx.ejs',
target: `src/components/${name}.tsx`,
props: { name, style: 'functional' }
})
Helper functions:
props.camelCase - camelCase conversion
props.pascalCase - PascalCase conversion
props.kebabCase - kebab-case conversion
- Reference:
scripts/template-helpers.ts
Filesystem Operations
Common operations (fs-jetpack):
// Read/write files
const config = await filesystem.read('config.json', 'json')
await filesystem.write('output.txt', data)
// Directory operations
await filesystem.dir('src/components')
const files = filesystem.find('src', { matching: '*.ts' })
// Copy/move/remove
await filesystem.copy('template', 'output')
await filesystem.move('old.txt', 'new.txt')
await filesystem.remove('temp')
Path utilities:
filesystem.path('src', 'commands') // Join paths
filesystem.cwd() // Current directory
filesystem.separator // OS-specific separator
HTTP Utilities
API interactions:
const api = http.create({
baseURL: 'https://api.example.com',
headers: { 'Authorization': 'Bearer token' }
})
const response = await api.get('/users')
const result = await api.post('/users', { name: 'John' })
Error handling:
if (!response.ok) {
print.error(response.problem)
return
}
Interactive Prompts
User input patterns:
// Ask question
const result = await prompt.ask({
type: 'input',
name: 'name',
message: 'What is your name?'
})
// Confirm action
const proceed = await prompt.confirm('Continue?')
// Select from list
const choice = await prompt.ask({
type: 'select',
name: 'framework',
message: 'Choose framework:',
choices: ['React', 'Vue', 'Angular']
})
Multi-select and complex forms:
- Reference:
examples/prompts/multi-select.ts
- See:
templates/toolbox/prompt-examples.ts.ejs
Plugin Architecture
Create extensible plugins:
// Plugin structure
export default (toolbox) => {
const { filesystem, template } = toolbox
// Add custom extension
toolbox.myFeature = {
doSomething: () => { /* ... */ }
}
}
Load plugins:
cli.plugins('./node_modules', { matching: 'mycli-*' })
cli.plugins('./plugins', { matching: '*.js' })
Plugin examples:
- Reference:
examples/plugin-system/custom-plugin.ts
- See:
templates/plugins/plugin-template.ts.ejs
Print Utilities
Colorful output:
print.info('Information message')
print.success('Success message')
print.warning('Warning message')
print.error('Error message')
print.highlight('Highlighted text')
print.muted('Muted text')
Spinners and progress:
const spinner = print.spin('Loading...')
await doWork()
spinner.succeed('Done!')
// Or fail
spinner.fail('Something went wrong')
Tables and formatting:
print.table([
['Name', 'Age'],
['John', '30'],
['Jane', '25']
])
System Commands
Execute external commands:
const output = await system.run('npm install')
const result = await system.exec('git status')
// Spawn with options
await system.spawn('npm run build', { stdio: 'inherit' })
Check command availability:
const hasGit = await system.which('git')
File Patching
- Modify existing files:
// Add line after pattern
await patching.update('package.json', (content) => {
const pkg = JSON.parse(content)
pkg.scripts.build = 'tsc'
return JSON.stringify(pkg, null, 2)
})
// Insert import statement
await patching.insert('src/index.ts', 'import { Router } from "express"')
Validation Scripts
Use these scripts to validate Gluegun CLI implementations:
scripts/validate-cli-structure.sh - Check directory structure
scripts/validate-commands.sh - Verify command format
scripts/validate-templates.sh - Check template syntax
scripts/test-cli-build.sh - Run full CLI build test
Templates
Command Templates
templates/commands/basic-command.ts.ejs - Simple command
templates/commands/generator-command.ts.ejs - File generator
templates/commands/api-command.ts.ejs - HTTP interaction
Extension Templates
templates/extensions/custom-toolbox.ts.ejs - Toolbox extension
templates/extensions/helper-functions.ts.ejs - Utility functions
Plugin Templates
templates/plugins/plugin-template.ts.ejs - Plugin structure
templates/plugins/plugin-with-commands.ts.ejs - Plugin with commands
Toolbox Templates
templates/toolbox/template-examples.ejs - Template patterns
templates/toolbox/prompt-examples.ts.ejs - Prompt patterns
templates/toolbox/filesystem-examples.ts.ejs - Filesystem patterns
Examples
Basic CLI Example
See examples/basic-cli/ for complete working CLI:
- Simple command structure
- Template generation
- User prompts
- File operations
Plugin System Example
See examples/plugin-system/ for extensible architecture:
- Plugin loading
- Custom toolbox extensions
- Command composition
Template Generator Example
See examples/template-generator/ for advanced patterns:
- Multi-file generation
- Conditional templates
- Helper functions
Best Practices
Command Organization
- One command per file
- Group related commands in subdirectories
- Use clear, descriptive command names
Template Design
- Keep templates simple and focused
- Use helper functions for complex logic
- Document template variables
Error Handling
- Check HTTP response status
- Validate user input from prompts
- Provide helpful error messages
Plugin Architecture
- Make plugins optional
- Document plugin interfaces
- Version plugin APIs
Testing
- Test commands in isolation
- Mock filesystem operations
- Validate template output
Security Considerations
- Never hardcode API keys in templates
- Use environment variables for secrets
- Validate all user input from prompts
- Sanitize file paths from parameters
- Check filesystem permissions before operations
Requirements
- Node.js 14+ or TypeScript 4+
- Gluegun package:
npm install gluegun
- EJS for templates (included)
- fs-jetpack for filesystem (included)
- enquirer for prompts (included)
Related Documentation
Purpose: Enable rapid CLI development with Gluegun patterns and best practices
Load when: Building CLI tools, command structures, template systems, or plugin architectures
1---2name: gluegun-patterns3description: Gluegun CLI toolkit patterns for TypeScript-powered command-line apps. Use when building CLI tools, creating command structures, implementing template systems, filesystem operations, HTTP utilities, prompts, or plugin architectures with Gluegun.4---56# Gluegun CLI Toolkit Patterns78Provides comprehensive patterns and templates for building TypeScript-powered CLI applications using the Gluegun toolkit. Gluegun offers parameters, templates, filesystem operations, HTTP utilities, prompts, and extensible plugin architecture.910## Core Capabilities1112Gluegun provides these essential toolbox features:13141. **Parameters** - Command-line arguments and options parsing152. **Template** - EJS-based file generation from templates163. **Filesystem** - File and directory operations (fs-jetpack)174. **System** - Execute external commands and scripts185. **HTTP** - API interactions with axios/apisauce196. **Prompt** - Interactive user input with enquirer207. **Print** - Colorful console output with colors/ora218. **Patching** - Modify existing file contents229. **Semver** - Version string manipulation2310. **Plugin System** - Extensible command architecture2425## Instructions2627### Building a Basic CLI28291. **Initialize Gluegun CLI structure:**30 ```typescript31 import { build } from 'gluegun'3233 const cli = build()34 .brand('mycli')35 .src(__dirname)36 .plugins('./node_modules', { matching: 'mycli-*', hidden: true })37 .help()38 .version()39 .create()40 ```41422. **Create command structure:**43 - Commands go in `src/commands/` directory44 - Each command exports a `GluegunCommand` object45 - Use templates from `templates/` directory46 - Reference template: `templates/commands/basic-command.ts.ejs`47483. **Implement command with toolbox:**49 ```typescript50 module.exports = {51 name: 'generate',52 run: async (toolbox) => {53 const { template, print, parameters } = toolbox54 const name = parameters.first5556 await template.generate({57 template: 'model.ts.ejs',58 target: `src/models/${name}.ts`,59 props: { name }60 })6162 print.success(`Generated ${name} model`)63 }64 }65 ```6667### Template System68691. **Template file structure:**70 - Store templates in `templates/` directory71 - Use EJS syntax: `<%= variable %>`, `<%- unescaped %>`72 - Reference: `templates/toolbox/template-examples.ejs`73742. **Generate files from templates:**75 ```typescript76 await template.generate({77 template: 'component.tsx.ejs',78 target: `src/components/${name}.tsx`,79 props: { name, style: 'functional' }80 })81 ```82833. **Helper functions:**84 - `props.camelCase` - camelCase conversion85 - `props.pascalCase` - PascalCase conversion86 - `props.kebabCase` - kebab-case conversion87 - Reference: `scripts/template-helpers.ts`8889### Filesystem Operations90911. **Common operations (fs-jetpack):**92 ```typescript93 // Read/write files94 const config = await filesystem.read('config.json', 'json')95 await filesystem.write('output.txt', data)9697 // Directory operations98 await filesystem.dir('src/components')99 const files = filesystem.find('src', { matching: '*.ts' })100101 // Copy/move/remove102 await filesystem.copy('template', 'output')103 await filesystem.move('old.txt', 'new.txt')104 await filesystem.remove('temp')105 ```1061072. **Path utilities:**108 ```typescript109 filesystem.path('src', 'commands') // Join paths110 filesystem.cwd() // Current directory111 filesystem.separator // OS-specific separator112 ```113114### HTTP Utilities1151161. **API interactions:**117 ```typescript118 const api = http.create({119 baseURL: 'https://api.example.com',120 headers: { 'Authorization': 'Bearer token' }121 })122123 const response = await api.get('/users')124 const result = await api.post('/users', { name: 'John' })125 ```1261272. **Error handling:**128 ```typescript129 if (!response.ok) {130 print.error(response.problem)131 return132 }133 ```134135### Interactive Prompts1361371. **User input patterns:**138 ```typescript139 // Ask question140 const result = await prompt.ask({141 type: 'input',142 name: 'name',143 message: 'What is your name?'144 })145146 // Confirm action147 const proceed = await prompt.confirm('Continue?')148149 // Select from list150 const choice = await prompt.ask({151 type: 'select',152 name: 'framework',153 message: 'Choose framework:',154 choices: ['React', 'Vue', 'Angular']155 })156 ```1571582. **Multi-select and complex forms:**159 - Reference: `examples/prompts/multi-select.ts`160 - See: `templates/toolbox/prompt-examples.ts.ejs`161162### Plugin Architecture1631641. **Create extensible plugins:**165 ```typescript166 // Plugin structure167 export default (toolbox) => {168 const { filesystem, template } = toolbox169170 // Add custom extension171 toolbox.myFeature = {172 doSomething: () => { /* ... */ }173 }174 }175 ```1761772. **Load plugins:**178 ```typescript179 cli.plugins('./node_modules', { matching: 'mycli-*' })180 cli.plugins('./plugins', { matching: '*.js' })181 ```1821833. **Plugin examples:**184 - Reference: `examples/plugin-system/custom-plugin.ts`185 - See: `templates/plugins/plugin-template.ts.ejs`186187### Print Utilities1881891. **Colorful output:**190 ```typescript191 print.info('Information message')192 print.success('Success message')193 print.warning('Warning message')194 print.error('Error message')195 print.highlight('Highlighted text')196 print.muted('Muted text')197 ```1981992. **Spinners and progress:**200 ```typescript201 const spinner = print.spin('Loading...')202 await doWork()203 spinner.succeed('Done!')204205 // Or fail206 spinner.fail('Something went wrong')207 ```2082093. **Tables and formatting:**210 ```typescript211 print.table([212 ['Name', 'Age'],213 ['John', '30'],214 ['Jane', '25']215 ])216 ```217218### System Commands2192201. **Execute external commands:**221 ```typescript222 const output = await system.run('npm install')223 const result = await system.exec('git status')224225 // Spawn with options226 await system.spawn('npm run build', { stdio: 'inherit' })227 ```2282292. **Check command availability:**230 ```typescript231 const hasGit = await system.which('git')232 ```233234### File Patching2352361. **Modify existing files:**237 ```typescript238 // Add line after pattern239 await patching.update('package.json', (content) => {240 const pkg = JSON.parse(content)241 pkg.scripts.build = 'tsc'242 return JSON.stringify(pkg, null, 2)243 })244245 // Insert import statement246 await patching.insert('src/index.ts', 'import { Router } from "express"')247 ```248249## Validation Scripts250251Use these scripts to validate Gluegun CLI implementations:252253- `scripts/validate-cli-structure.sh` - Check directory structure254- `scripts/validate-commands.sh` - Verify command format255- `scripts/validate-templates.sh` - Check template syntax256- `scripts/test-cli-build.sh` - Run full CLI build test257258## Templates259260### Command Templates261- `templates/commands/basic-command.ts.ejs` - Simple command262- `templates/commands/generator-command.ts.ejs` - File generator263- `templates/commands/api-command.ts.ejs` - HTTP interaction264265### Extension Templates266- `templates/extensions/custom-toolbox.ts.ejs` - Toolbox extension267- `templates/extensions/helper-functions.ts.ejs` - Utility functions268269### Plugin Templates270- `templates/plugins/plugin-template.ts.ejs` - Plugin structure271- `templates/plugins/plugin-with-commands.ts.ejs` - Plugin with commands272273### Toolbox Templates274- `templates/toolbox/template-examples.ejs` - Template patterns275- `templates/toolbox/prompt-examples.ts.ejs` - Prompt patterns276- `templates/toolbox/filesystem-examples.ts.ejs` - Filesystem patterns277278## Examples279280### Basic CLI Example281See `examples/basic-cli/` for complete working CLI:282- Simple command structure283- Template generation284- User prompts285- File operations286287### Plugin System Example288See `examples/plugin-system/` for extensible architecture:289- Plugin loading290- Custom toolbox extensions291- Command composition292293### Template Generator Example294See `examples/template-generator/` for advanced patterns:295- Multi-file generation296- Conditional templates297- Helper functions298299## Best Practices3003011. **Command Organization**302 - One command per file303 - Group related commands in subdirectories304 - Use clear, descriptive command names3053062. **Template Design**307 - Keep templates simple and focused308 - Use helper functions for complex logic309 - Document template variables3103113. **Error Handling**312 - Check HTTP response status313 - Validate user input from prompts314 - Provide helpful error messages3153164. **Plugin Architecture**317 - Make plugins optional318 - Document plugin interfaces319 - Version plugin APIs3203215. **Testing**322 - Test commands in isolation323 - Mock filesystem operations324 - Validate template output325326## Security Considerations327328- Never hardcode API keys in templates329- Use environment variables for secrets330- Validate all user input from prompts331- Sanitize file paths from parameters332- Check filesystem permissions before operations333334## Requirements335336- Node.js 14+ or TypeScript 4+337- Gluegun package: `npm install gluegun`338- EJS for templates (included)339- fs-jetpack for filesystem (included)340- enquirer for prompts (included)341342## Related Documentation343344- Gluegun Official Docs: https://infinitered.github.io/gluegun/345- GitHub Repository: https://github.com/infinitered/gluegun346- EJS Templates: https://ejs.co/347- fs-jetpack: https://github.com/szwacz/fs-jetpack348349---350351**Purpose**: Enable rapid CLI development with Gluegun patterns and best practices352**Load when**: Building CLI tools, command structures, template systems, or plugin architectures