Spice comes with a batteries-included CLI parser to make it easy to build command line interfaces. The following example shows how to build a simple CLI interface with a few sub-commands and options.
// app-name.spiceimport"std/io/cli-parser";f<int>main(intargc,string[]argv){CliParsercli=CliParser("app-name","Short description of the app");returncli.parse(argc,argv);}
These two lines of code provide you with a fully functional CLI parser. The CliParser constructor takes two arguments: - app-name: string - The name of the application. This will be used in the help text. - app-description: string - A short description of the application. This will also be used in the help text.
The CLI parser automatically provides two flags, one for printing the help text and one for printing the version info. So if we compile and run this code, we will get the following output:
// app-name.spiceimport"std/io/cli-parser";f<int>main(intargc,string[]argv){CliParsercli=CliParser("app-name","Short description of the app");cli.setVersion("v1.0.0");cli.setFooter("(c) 2024 by John Doe");boolflagValue=false;cli.addFlag("--hi",flagValue,"Say Hi");cli.parse(argc,argv);ifflagValue{printf("Hi!\n");}}
$ ./app-name
Short description of the appUsage: ./app-name [options]Flags:--help,-h Print this help message--version,-v Print version info--hi Say Hi(c)2024 by John Doe
When we run the program with the --hi flag, we get the following output:
// app-name.spiceimport"std/io/cli-parser";f<int>main(intargc,string[]argv){CliParsercli=CliParser("app-name","Short description of the app");cli.setVersion("v1.0.0");cli.setFooter("(c) 2024 by John Doe");CliSubcommand&greet=cli.addSubcommand("greet","Greet someone");CliSubcommand&walk=cli.addSubcommand("walk","Walk somewhere");cli.parse(argc,argv);}
Each subcommand comes with its own --help flag out of the box, that prints the help text for that specific subcommand. Subcommands can also have their own sub-commands. In other words, they can be nested:
// app-name.spiceimport"std/io/cli-parser";f<int>main(intargc,string[]argv){CliParsercli=CliParser("app-name","Short description of the app");cli.setVersion("v1.0.0");cli.setFooter("(c) 2024 by John Doe");CliSubcommand&greet=cli.addSubcommand("greet","Greet someone");CliSubcommand&greetFriendly=greet.addSubcommand("friendly","Greet someone in a friendly way");CliSubcommand&greetFormal=greet.addSubcommand("formal","Greet someone in a formal way");CliSubcommand&walk=cli.addSubcommand("walk","Walk somewhere");cli.parse(argc,argv);}