A template for quickly bootstrapping a Command Line Interface (CLI) project in JavaScript.
Are repetitive tasks and inconsistent command-line interfaces stealing your peace of mind? Do you yearn for a development workflow that feels intuitive, efficient, and genuinely enjoyable? The cli-pattern is your pathway to clarity and calm, empowering you to reclaim control and find your development zen.
Ready to unlock your full potential? With cli-pattern, you'll experience a profound impact on your development process, leading to:
- Streamlined Development: Rapidly build new CLI commands with a clear, consistent structure.
- Enhanced Maintainability: Easily understand and update existing commands, reducing technical debt.
- Improved User Experience: Provide your users with predictable and intuitive command-line tools.
- Reduced Errors: Minimize bugs through a standardized approach to command definition and execution.
cli-pattern offers a robust set of features to empower your CLI development:
- Modular Command Structure: Organize your commands into distinct, manageable modules.
- Automatic Command Loading: Commands are automatically discovered and loaded, simplifying setup.
- Consistent API: A standardized interface for defining command actions, options, and arguments.
- Built-in Logging: Integrated logging utilities for clear feedback and debugging.
- Extensible Design: Easily integrate with other libraries and tools to extend functionality.
- Clear Project Layout: A well-defined directory structure that promotes best practices.
This section outlines the directory and file structure of the project.
/
├── bin # Folder: Contains executable scripts.
│ └── cli.js # Executable: Main CLI entry point script.
├── config # Folder: Contains configuration files.
│ └── default.config.js # Configuration: Default configuration settings.
├── src # Folder: Contains source code files.
│ ├── commands # Folder: Contains definitions for CLI commands.
│ │ ├── example # Folder: Example CLI command implementation.
│ │ │ ├── action.js # Source Code: Action logic for the example command.
│ │ │ └── index.js # Source Code: Definition and setup for the example command.
│ │ ├── quickly # Folder: Quickly CLI command implementation.
│ │ │ ├── action.js # Source Code: Action logic for the quickly command.
│ │ │ └── index.js # Source Code: Definition and setup for the quickly command.
│ │ └── sample # Folder: Sample CLI command implementation.
│ │ ├── action.js # Source Code: Action logic for the sample command.
│ │ └── index.js # Source Code: Definition and setup for the sample command.
│ ├── utils # Folder: Contains utility functions.
│ │ ├── loadCommands.js # Source Code: Utility for loading CLI commands.
│ │ └── logger.js # Source Code: Utility for logging messages.
│ └── index.js # Source Code: Main entry point for the application source.
├── .gitignore # Configuration: Specifies intentionally untracked files to ignore.
├── .npmcheckrc.json
├── .prettierignore # Configuration: Specifies files to be ignored by Prettier.
├── .prettierrc.json # Configuration: Defines Prettier formatting rules.
├── CHANGELOG.md
├── CLI_API.md # Documentation: Provides API reference for the CLI.
├── CONTRIBUTING.md # Documentation: Guidelines for contributing to the project.
├── LICENSE # Legal: Project license information.
├── md.config.js # Configuration: Configuration for markdown processing.
├── package-lock.json # Dependency Management: Records the exact dependency tree.
├── package.json # Configuration: Project metadata and dependency definitions.
├── README.md # Documentation: Project overview and instructions.
├── RULES_OF_CONDUCT.md # Documentation: Defines rules of conduct for the project community.
└── SCRIPTS.md
This section guides you on how to leverage cli-pattern to create new commands and options, and highlights the powerful features available out-of-the-box.
To create a new command, follow these simple steps:
-
Create a new directory under
src/commands. The directory name will be your command name. For instance, to create amycommandcommand, createsrc/commands/mycommand/. -
Inside your new command directory, create two files:
index.js: This file defines your command's metadata, arguments, and options usingcommander.js.action.js: This file contains the core logic that executes when your command is called.
Here's an example based on the
examplecommand:src/commands/mycommand/index.jsconst action = require('./action'); module.exports = (program, mergedConfig) => { program .command('mycommand') .description('A brief description of what mycommand does.') .argument('<requiredArg>', 'A required argument for mycommand.') .option( '-o, --optional-option <value>', 'An optional option for mycommand.', 'defaultValue' ) .action(async (requiredArg, options, command) => { const commandConfig = mergedConfig.mycommand || {}; const finalOptions = { ...mergedConfig, ...commandConfig, ...command.opts(), ...options, requiredArg, }; await action(finalOptions, command.logger); }); };
src/commands/mycommand/action.jsmodule.exports = async (options, logger) => { logger.info('mycommand action executed!'); logger.debug('Received options for mycommand:', options); // Your command's core logic goes here. // You can access arguments and options via the 'options' object. };
-
Your new command is automatically loaded! Once these files are in place,
cli-patternautomatically discovers and registers yourmycommand. You can then run it from your terminal:./bin/cli.js mycommand <value_for_requiredArg> --optional-option <value>
cli-pattern leverages commander.js for defining command-line interfaces. You can define arguments and options directly in your command's index.js file:
- Arguments: Use
.argument('<name>', 'description')for required arguments or[name]for optional ones. - Options: Use
.option('-s, --long-name <value>', 'description', 'defaultValue')to define options.
Refer to the commander.js documentation for advanced argument and option parsing.
When you create commands with cli-pattern, you automatically benefit from:
- Automatic Command Discovery: No need to manually register new commands; just create the files in the correct structure.
- Integrated Help System:
commander.jsautomatically generates comprehensive help messages for your CLI and individual commands. - Configurable Logging: Utilize the
loggerobject passed to youraction.jsfor structured and configurable logging (info,warn,error,debug,verbose). - Configuration Merging: Command-specific configurations are automatically merged with global settings, providing a flexible configuration hierarchy.
- Version Display: The CLI automatically handles displaying the version defined in your
package.json.
This project utilizes a variety of npm scripts to automate tasks such as testing, linting, and building. A comprehensive list and description of these scripts can be found in the CLI Scripts Documentation.
For detailed information on available commands, arguments, and options, please refer to the CLI API Documentation.
Contributions are welcome! Please read our contributing guidelines to get started.
This project is licensed under the MIT License. See the LICENSE file for details.
- commander — the complete solution for node.js command-line programs
- cosmiconfig — Find and load configuration from a package.json property, rc file, TypeScript module, and more!
- jest — Delightful JavaScript Testing.
- markdown-magic-scripts — Automatically generate a dynamic, customizable dashboard of your npm scripts in your README.md using this markdown-magic transform. Keep your project documentation in sync with your package.json.
- markdown-magic-transform-acknowledgements — A markdown-magic transform that auto-generates an Acknowledgements section for contributors, dependencies, and custom entries.
- markdown-magic-transform-badges — No description available
- markdown-magic-transform-treefile-extended — A markdown-magic transform to generate a dynamic file tree in your markdown files. This extended version provides additional options for customizing the output.
- prettier — Prettier is an opinionated code formatter
- prettier-plugin-packagejson — Prettier package.json plugin to make the order of properties nice.