This project is an example starter project for the Gimme a CLI library.
This project can be forked and used as a starting point for creating your own CLI.
The starter project includes:
- Gimme a CLI - a Java library for creating quick and easy CLIs using JCommander and Spring dependency injection.
- An example
Hello World
command. - An example
--version
command. - Shadow Plugin gradle setup to make it easy to distribute your CLI. The
Shadow plugin creates a fat jar with all dependencies,
sh
and.bat
wrapper scripts, and.tar
and.zip
distributions.
-
Install the Java 11 OpenJDK.
-
Fork this project.
-
Find/replace
mycli
with the name of your CLI. -
Define one or more commands for your CLI by implementing the Command interface. Optionally use JCommander annotations to define command arguments and options.
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.nike.gimme.a.cli.Command; @Parameters(commandNames = "hello", commandDescription = "Prints \"Hello <name>\" to the terminal") public class HelloWorldCommand implements Command { private final Logger log = LoggerFactory.getLogger(getClass()); @Parameter(names = {"--name"}, required = true) private String name; @Override public void execute() { log.info("Hello " + name); } }
Commands are automatically instantiated as Spring beans (e.g. dependencies can be supplied via constructor injection, etc).
-
Build and run
# Create the distribution ./gradlew shadowDistTar # Extract it tar xf build/distributions/mycli-shadow-1.0.0-SNAPSHOT.tar # Run the CLI mycli-shadow-1.0.0-SNAPSHOT/bin/mycli --help
-
Optionally define gradle tasks for running CLI commands
task helloWorldFromGradle(type: CliExec) { description = "Example of defining a CLI command as a Gradle task" // arguments to pass to the application args 'hello', '--name', 'world from gradle' }
This lets you quickly run commands locally without building archives.
- Gimme a CLI - the library that this project is a "starter project" for.
- JCommander - a library for CLI argument parsing.
- Spring's IoC - a library for dependency injection.
- Shadow Plugin - a gradle plugin for creating a single output jar. Makes it easy to distribute your CLI to share with others.