gemini-2.5-pro-preview-05-06· Google LMArena Human Preference 140K
rust clap: how to create cli of toggle on, toggle off and toggle
- User
rust clap: how to create cli of
toggle on,toggle offandtoggle - Assistant
Okay, let's create a CLI tool using
clap(version 4, using the derive API, which is the most common and ergonomic way). This tool will manage a simple on/off state, persisting it in a file.Goal:
my_toggle_cli toggle on: Turns the state to ON.my_toggle_cli toggle off: Turns the state to OFF.my_toggle_cli toggle: Flips the current state (ON -> OFF, OFF -> ON).- Bonus:
my_toggle_cli status: Shows the current state.
1. Setup
Cargo.toml[package] name = "my_toggle_cli" version = "0.1.0" edition = "2021" [dependencies] clap = { version = "4.4", features = ["derive"] } anyhow = "1.0" # For easy error handling dirs = "5.0" # For finding appropriate config/data directories2. Create
src/main.rsuse clap::{Parser, Subcommand}; use std::fs; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; // Using anyhow for convenient error handling const STATE_FILE_NAME: &str = ".my_toggle_state"; // Hidden file in user's home or config // Enum to represent the state #[derive(Debug, PartialEq, Clone, Copy)] enum ToggleState { On, Off, } impl ToggleState { fn from_str(s: &str) -> Self { match s.trim().to_lowercase().as_str() { "on" => ToggleState::On, _ => ToggleState::Off, // Default to Off if unknown or empty } } fn to_str(&self) -> &'static str { match self { ToggleState::On => "on", ToggleState::Off => "off", } } fn flip(&self) -> Self { match self { ToggleState::On => ToggleState::Off, ToggleState::Off => ToggleState::On, } } } // --- Clap Argument Parsing Structs --- #[derive(Parser, Debug)] #[clap(name = "my-toggle-cli", version = "0.1.0", author = "Your Name")] #[clap(about = "A simple CLI to toggle an on/off state", long_about = None)] struct Cli { #[clap(subcommand)] command: Commands, } #[derive(Subcommand, Debug)] enum Commands { /// Manage the toggle state (on, off, or flip) Toggle(ToggleArgs), /// Show the current toggle state Status, } #[derive(Parser, Debug)] // clap::Args would also work here, Parser is fine for sub-args struct ToggleArgs { #[clap(subcommand)] action: Option<ToggleAction>, // Optional: if None, it means "flip" } #[derive(Subcommand, Debug)] enum ToggleAction { /// Turn the toggle ON On, /// Turn the toggle OFF Off, } // --- State Management Functions --- fn get_state_file_path() -> Result<PathBuf> { // Prefer a config directory if available, otherwise home directory let path = dirs::config_dir() .or_else(dirs::home_dir) .context("Could not determine config or home directory")? .join(STATE_FILE_NAME); Ok(path) } fn read_state(file_path: &Path) -> Result<ToggleState> { if !file_path.exists() { return Ok(ToggleState::Off); // Default to Off if file doesn't exist } let content = fs::read_to_string(file_path) .with_context(|| format!("Failed to read state file: {:?}", file_path))?; Ok(ToggleState::from_str(&content)) } fn write_state(file_path: &Path, state: ToggleState) -> Result<()> { fs::write(file_path, state.to_str()) .with_context(|| format!("Failed to write state file: {:?}", file_path))?; Ok(()) } // --- Main Logic --- fn main() -> Result<()> { let cli = Cli::parse(); let state_file_path = get_state_file_path()?; match cli.command { Commands::Toggle(toggle_args) => { let mut current_state = read_state(&state_file_path)?; let new_state = match toggle_args.action { Some(ToggleAction::On) => { if current_state == ToggleState::On { println!("Already ON."); return Ok(()); } ToggleState::On } Some(ToggleAction::Off) => { if current_state == ToggleState::Off { println!("Already OFF."); return Ok(()); } ToggleState::Off } None => { // Flip current_state.flip() } }; write_state(&state_file_path, new_state)?; println!("State set to: {}", new_state.to_str().to_uppercase()); } Commands::Status => { let current_state = read_state(&state_file_path)?; println!("Current state: {}", current_state.to_str().to_uppercase()); } } Ok(()) }3. How it Works:
Clistruct: The main entry point for parsing. It expects one subcommand.Commandsenum: Defines the top-level subcommands:ToggleandStatus.ToggleArgsstruct: This is used by theTogglecommand. It has anactionfield.ToggleActionenum: This is a sub-subcommand forToggle. It can beOnorOff.action: Option<ToggleAction>:- If the user types
my_toggle_cli toggle on,actionwill beSome(ToggleAction::On). - If the user types
my_toggle_cli toggle off,actionwill beSome(ToggleAction::Off). - If the user types
my_toggle_cli toggle(with nothing after),actionwill beNone. This is how we achieve the "flip" behavior.
- If the user types
- State Management:
ToggleStateenum: Represents the internal state.get_state_file_path(): Tries to find a suitable location (config or home dir) for the state file (.my_toggle_state).read_state(): Reads the state ("on" or "off") from the file. Defaults toOffif the file doesn't exist or is invalid.write_state(): Writes the new state to the file.
- Error Handling:
anyhow::Resultandwith_contextprovide cleaner error messages.
4. Build and Run:
cargo build # Test it out ./target/debug/my_toggle_cli status # Expected: Current state: OFF (or whatever the default is on first run) ./target/debug/my_toggle_cli toggle on # Expected: State set to: ON ./target/debug/my_toggle_cli status # Expected: Current state: ON ./target/debug/my_toggle_cli toggle on # Expected: Already ON. ./target/debug/my_toggle_cli toggle # Expected: State set to: OFF ./target/debug/my_toggle_cli status # Expected: Current state: OFF ./target/debug/my_toggle_cli toggle off # Expected: State set to: OFF (or Already OFF.) ./target/debug/my_toggle_cli toggle off # Expected: Already OFF. ./target/debug/my_toggle_cli --help # You'll see the help message generated by clapThis setup gives you the
toggle on,toggle off, andtoggle(flip) functionality you requested, along with astatuscommand and persistent state.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.