Skip to main content

CodexSubcommand

Derive Macro CodexSubcommand 

Source
#[derive(CodexSubcommand)]
Expand description

Derives subcommand routing logic for an Enum.

The CodexSubcommand derive macro automatically converts each variant of the enum into a CLI command. Variant names are converted to kebab-case to adhere to standard CLI naming conventions (e.g., BuildApp becomes build-app).

§Usage Example

use cirious_codex_derive::{CodexCommand, CodexSubcommand, CodexParser};

/// Global arguments shared across all CLI commands.
#[derive(Debug, Clone)]
pub struct GlobalArgs {
 /// Enables verbose mode for detailed diagnostic logging.
 pub verbose: bool,

 /// Optional path to a configuration file.
 pub config_path: Option<String>,
}

/// A trait defining the contract for any command that utilizes global arguments.
pub trait CodexCommand {
 /// Returns a reference to the global arguments.
 fn global_args(&self) -> &GlobalArgs;
}


/// Arguments specific to the build command.
#[derive(CodexParser, CodexCommand, Debug)]
pub struct BuildArgs {
 /// Global arguments injected by the `CodexCommand` macro.
 pub global: GlobalArgs,
 /// Example argument for the build process.
 #[codex(aliase = "", command = "build-example", default_value = "app-example")]
 pub build_example: String,
}

/// Arguments specific to the run command.
#[derive(CodexParser, CodexCommand, Debug)]
pub struct RunArgs {
 /// Global arguments injected by the `CodexCommand` macro.
 pub global: GlobalArgs,
 /// Example argument for the execution process.
 #[codex(aliase = "", command = "run-example", default_value = "app-example")]
  pub run_example: String,
}

//The central subcommand router for the CLI application.
#[derive(CodexSubcommand)]
enum MyCLI {
  /// Build command variant.
  Build(BuildArgs),
  /// Run command variant.
  Run(RunArgs),
}


fn main() {
  let command = MyCLI::parse();
  match command {
    MyCLI::Build(args) => println!("Construindo com {args:?}"),
    MyCLI::Run(args) => println!("Executando com {args:?}"),
  }
}

§How it works

  • Routing: It consumes the first command-line argument (after the executable name) to determine the enum variant.
  • Iterator Sharing: It passes the remaining arguments directly to the inner struct’s parse_cli method.
  • Validation: If the provided command does not match any enum variant, it prints a stylized error message.