### Install zfish from GitHub Releases (Backup) Source: https://github.com/jeetkarena/zfish/blob/main/PACKAGES.md This snippet demonstrates downloading and verifying a zfish release artifact directly from GitHub Releases. It includes steps for downloading the crate file, checksums, and verifying integrity using `sha256sum` or `sha512sum`. This is a backup method for installation. ```bash # Set the version you want VERSION="0.1.10" # Download the .crate file wget https://github.com/JeetKarena/ZFish/releases/download/v${VERSION}/zfish-${VERSION}.crate # Download checksums wget https://github.com/JeetKarena/ZFish/releases/download/v${VERSION}/zfish-${VERSION}.crate.sha256 wget https://github.com/JeetKarena/ZFish/releases/download/v${VERSION}/zfish-${VERSION}.crate.sha512 # Verify integrity (choose one) sha256sum -c zfish-${VERSION}.crate.sha256 sha512sum -c zfish-${VERSION}.crate.sha512 # Extract and use tar -xzf zfish-${VERSION}.crate ``` -------------------------------- ### Example Usage of ZFish Argument Features (Rust) Source: https://github.com/jeetkarena/zfish/blob/main/V0.2.1_IMPLEMENTATION_SUMMARY.md Demonstrates the practical application of the implemented argument parsing features in a real-world CLI scenario. This example serves as a guide for users and developers. ```rust // examples/10_arg_features_v2.rs // This file demonstrates all 8 implemented features with clear comments and use cases. ``` -------------------------------- ### Install zfish in GitHub Actions CI Source: https://github.com/jeetkarena/zfish/blob/main/PACKAGES.md This snippet provides a GitHub Actions workflow step to download and extract the zfish crate. It is used within a CI/CD pipeline to ensure the necessary library is available during the build process. ```yaml - name: Install zfish run: | VERSION="0.1.10" wget https://github.com/JeetKarena/ZFish/releases/download/v${VERSION}/zfish-${VERSION}.crate tar -xzf zfish-${VERSION}.crate ``` -------------------------------- ### Create Git-Style Subcommands with zfish command Source: https://github.com/jeetkarena/zfish/blob/main/README.md Builds a Git-style command-line interface using `zfish::command`. This example defines a main application with version and description, and includes subcommands like 'init' and 'build' with their own arguments. It relies on the `zfish` crate for CLI structure. ```rust use zfish::command::{App, Command, Arg}; fn main() { let app = App::new("myapp") .version("1.0.0") .about("My awesome CLI") .arg(Arg::new("verbose").short('v').long("verbose")) .subcommand( Command::new("init") .about("Initialize a new project") .arg(Arg::new("name").required(true)) ) .subcommand( Command::new("build") .about("Build the project") .arg(Arg::new("release").long("release")) ); let matches = app.get_matches(); match matches.subcommand() { Some(("init", sub_matches)) => { let name = sub_matches.value_of("name").unwrap(); println!("Initializing: {}", name); } Some(("build", sub_matches)) => { if sub_matches.is_present("release") { println!("Building in release mode"); } } _ => println!("Use --help for usage"), } } ``` -------------------------------- ### Install zfish in GitLab CI Source: https://github.com/jeetkarena/zfish/blob/main/PACKAGES.md This snippet demonstrates how to install the zfish crate within a GitLab CI pipeline. It downloads the crate file and extracts it, ensuring the library is available for subsequent build or test stages. ```yaml install_zfish: script: - VERSION="0.1.10" - wget https://github.com/JeetKarena/ZFish/releases/download/v${VERSION}/zfish-${VERSION}.crate - tar -xzf zfish-${VERSION}.crate ``` -------------------------------- ### Rust Documentation Example with Panics - Rust Source: https://github.com/jeetkarena/zfish/blob/main/CONTRIBUTING.md Demonstrates documentation comments for a Rust function, including arguments, expected panics, and usage examples within a ```` ```rust ```` block. This follows the `rustdoc` convention for generating API documentation. ```rust /// Creates a new progress bar with the specified total /// /// # Arguments /// * `total` - The maximum value for the progress bar /// /// # Panics /// Panics if `total` is 0 /// /// # Examples /// ``` /// use zfish::ProgressBar; /// /// let pb = ProgressBar::new(100); /// pb.set(50); // 50% /// ``` pub fn new(total: usize) -> Self { assert!(total > 0, "total must be greater than 0"); Self { total, current: 0 } } ``` -------------------------------- ### ZFish Development Setup and Testing Commands Source: https://github.com/jeetkarena/zfish/blob/main/README.md Provides essential bash commands for setting up the ZFish development environment, running tests, and building documentation. Includes commands for cloning the repository, running all tests, running tests in single-threaded mode to prevent environment variable conflicts, and building/opening the project documentation. ```bash # Clone the repository git clone https://github.com/JeetKarena/ZFish.git cd zfish # Run tests carp test # Run tests (single-threaded to avoid env var conflicts) carp test -- --test-threads=1 # Build documentation carp doc --open # Run examples carp run --example 01_hello_world carp run --example 02_argument_parsing carp run --example 03_colored_text carp run --example 04_progress_bar carp run --example 05_logger carp run --example 06_terminal_control carp run --example 07_interactive_prompts carp run --example 08_complete_cli ``` -------------------------------- ### Hello World with Color Styling in Rust Source: https://github.com/jeetkarena/zfish/blob/main/README.md Basic example demonstrating zfish color painting functionality. Uses the Color enum to apply ANSI color styling to console output strings. Requires zfish crate and outputs colored text with success, error, and warning indicators to stdout. ```rust use zfish::Color; fn main() { println!("{}", Color::Green.paint("✓ Success!")); println!("{}", Color::Red.paint("✗ Error!")); println!("{}", Color::Yellow.paint("⚠ Warning!")); } ``` -------------------------------- ### Format Data in Beautiful Tables with zfish table Source: https://github.com/jeetkarena/zfish/blob/main/README.md Creates visually appealing tables using `zfish::table`. This example shows how to initialize a table with headers, set box styles (e.g., rounded), align columns, add rows of data, and print the formatted table to the console. It requires the `zfish` crate. ```rust use zfish::table::{Table, BoxStyle, Alignment}; use zfish::Color; fn main() { let mut table = Table::new(vec!["Name", "Language", "Stars"]); table.set_box_style(BoxStyle::Rounded); table.set_column_alignment(2, Alignment::Right); table.add_row(vec!["zfish", "Rust", "⭐⭐⭐⭐⭐"]); table.add_row(vec!["clap", "Rust", "⭐⭐⭐⭐"]); table.add_row(vec!["cobra", "Go", "⭐⭐⭐"]); table.print(); // Output: // ╭──────────┬──────────┬───────╮ // │ Name │ Language │ Stars │ // ├──────────┼──────────┼───────┤ // │ zfish │ Rust │ ⭐⭐⭐⭐⭐ │ // │ clap │ Rust │ ⭐⭐⭐⭐ │ // │ cobra │ Go │ ⭐⭐⭐ │ // ╰──────────┴──────────┴───────╯ } ``` -------------------------------- ### Basic CLI App with Subcommands in Rust Source: https://github.com/jeetkarena/zfish/blob/main/docs/SUBCOMMAND_IMPLEMENTATION.md Demonstrates the basic usage of the zfish command system to define an application, arguments, and subcommands. It shows how to create an App, add arguments and subcommands, parse matches, and access argument values or subcommand details. This example highlights the builder pattern for API design. ```rust use zfish::command::{App, Arg, Command}; let app = App::new("myapp") .version("1.0.0") .about("My application") .arg(Arg::new("verbose").short('v').long("verbose").takes_value(false)) .subcommand( Command::new("test") .about("Run tests") .arg(Arg::new("filter").long("filter")) ); let matches = app.get_matches(); if matches.is_flag_set("verbose") { println!("Verbose mode"); } if let Some(("test", sub)) = matches.subcommand() { if let Some(filter) = sub.value_of("filter") { println!("Running tests matching: {}", filter); } } ``` -------------------------------- ### Rust Test Organization Example - Rust Source: https://github.com/jeetkarena/zfish/blob/main/CONTRIBUTING.md Provides an example of how to organize unit tests within a Rust project using the `#[cfg(test)]` attribute and `mod tests`. It includes tests for creation, rendering, and handling invalid input for a ProgressBar. ```rust @cfg(test)] mod tests { use super::*; #[test] fn test_progress_bar_creation() { let pb = ProgressBar::new(100); assert_eq!(pb.total, 100); } #[test] fn test_progress_bar_rendering() { let pb = ProgressBar::new(100); let output = pb.render(50); assert!(output.contains("50%")); } #[test] #[should_panic(expected = "total must be greater than 0")] fn test_invalid_progress_bar() { ProgressBar::new(0); } } ``` -------------------------------- ### Rust Code Quality Example - Rust Source: https://github.com/jeetkarena/zfish/blob/main/CONTRIBUTING.md Illustrates good and bad practices for Rust code quality. The 'good' example shows clear documentation, purpose, and testability using doc comments and a public API. The 'bad' example is a minimal, undocumented function. ```rust // ✅ Good - clear, documented, tested /// Renders a progress bar to the terminal /// /// # Arguments /// * `current` - Current progress value /// * `total` - Total progress value /// /// # Examples /// ``` /// use zfish::ProgressBar; /// let pb = ProgressBar::new(100); /// pb.render(50); /// ``` pub fn render(&self, current: usize, total: usize) { // Implementation } // ❌ Bad - unclear, undocumented pub fn do_thing(&self, a: usize, b: usize) { // ... } ``` -------------------------------- ### Add zfish as Direct Git Dependency in Rust Source: https://github.com/jeetkarena/zfish/blob/main/PACKAGES.md This snippet illustrates how to include zfish directly from its Git repository, useful for using the latest development version or a specific tag. It configures the dependency in `Cargo.toml`. ```toml # Use the latest development version: zfish = { git = "https://github.com/JeetKarena/ZFish.git", branch = "main" } # Or a specific tag: zfish = { git = "https://github.com/JeetKarena/ZFish.git", tag = "v0.1.10" } ``` -------------------------------- ### Verify zfish Crate Integrity with Checksums Source: https://github.com/jeetkarena/zfish/blob/main/PACKAGES.md This snippet shows how to verify the integrity of a downloaded zfish crate file using SHA256 and SHA512 checksums. It requires the crate file and its corresponding checksum file, typically obtained from GitHub Releases. ```bash # SHA256 verification sha256sum zfish-0.1.10.crate # Should match: zfish-0.1.10.crate.sha256 # SHA512 verification sha512sum zfish-0.1.10.crate # Should match: zfish-0.1.10.crate.sha512 ``` -------------------------------- ### Add zfish Dependency to Rust Project (crates.io) Source: https://github.com/jeetkarena/zfish/blob/main/PACKAGES.md This snippet shows how to add the zfish library as a dependency to your Rust project using Cargo.toml or the `cargo add` command. This is the recommended method for stable releases. ```toml [dependencies] zfish = "0.1" ``` ```bash cargo add zfish ``` -------------------------------- ### Git-Style CLI Structure in Rust Source: https://github.com/jeetkarena/zfish/blob/main/docs/SUBCOMMAND_IMPLEMENTATION.md Illustrates how to structure a Git-like command-line interface using the zfish system. This example defines 'commit' and 'push' subcommands, each with their own specific arguments, showcasing how to handle required arguments and flags. It demonstrates the flexibility in defining complex CLI structures. ```rust let app = App::new("git") .subcommand( Command::new("commit") .arg(Arg::new("message").short('m').long("message").required(true)) .arg(Arg::new("all").short('a').takes_value(false)) ) .subcommand( Command::new("push") .arg(Arg::new("force").short('f').takes_value(false)) ); ``` -------------------------------- ### Migrate from Old Args API to New Command API in Rust Source: https://github.com/jeetkarena/zfish/blob/main/docs/SUBCOMMAND_IMPLEMENTATION.md Shows the migration path from the older `zfish::Args` API to the newer `zfish::command::App` API. The example contrasts how to parse arguments and check for flags in both versions, highlighting the builder pattern and explicit argument definition in the new API. ```rust use zfish::Args; let args = Args::parse(); if args.has_flag("verbose") { println!("Verbose mode"); } ``` ```rust use zfish::command::App; let app = App::new("myapp") .arg(Arg::new("verbose").short('v').long("verbose").takes_value(false)); let matches = app.get_matches(); if matches.is_flag_set("verbose") { println!("Verbose mode"); } ``` -------------------------------- ### Display Progress Bar with zfish ProgressBar Source: https://github.com/jeetkarena/zfish/blob/main/README.md Implements a progress bar to visualize task completion. This example uses `zfish::ProgressBar` to set and update the progress, along with `std::thread::sleep` to simulate work. It requires the `zfish` crate and standard library threading. ```rust use zfish::ProgressBar; use std::thread; use std::time::Duration; fn main() { let mut pb = ProgressBar::new(100); for i in 0..=100 { pb.set(i); thread::sleep(Duration::from_millis(50)); } pb.finish("✓ Complete!"); } ``` -------------------------------- ### Creating Formatted Tables in Rust Source: https://context7.com/jeetkarena/zfish/llms.txt Shows how to generate well-formatted tables in the console using the zfish library. Supports various box styles (single-line, rounded, double-line, heavy, ASCII), column alignment, indentation, and Unicode characters for rich output. ```rust use zfish::table::{Table, BoxStyle, Alignment}; use zfish::Color; fn main() { // Basic table with single-line borders let mut table = Table::new(vec!["Name", "Language", "Stars"]); table.add_row(vec!["zfish", "Rust", "⭐⭐⭐⭐⭐"]); table.add_row(vec!["clap", "Rust", "⭐⭐⭐⭐"]); table.add_row(vec!["cobra", "Go", "⭐⭐⭐"]); table.print(); // Rounded corners style let mut rounded = Table::new(vec!["Product", "Price", "Qty"]); rounded.set_box_style(BoxStyle::Rounded); rounded.set_column_alignment(1, Alignment::Right); // Right-align price rounded.set_column_alignment(2, Alignment::Right); // Right-align quantity rounded.add_row(vec!["Widget", "$19.99", "50"]); rounded.add_row(vec!["Gadget", "$29.99", "25"]); rounded.add_row(vec!["Doohickey", "$9.99", "100"]); rounded.print(); // Double-line borders let mut double = Table::new(vec!["ID", "Status", "Message"]); double.set_box_style(BoxStyle::Double); double.add_row(vec!["001", "✓ OK", "Process completed"]); double.add_row(vec!["002", "⚠ WARN", "Minor issue detected"]); double.add_row(vec!["003", "✗ ERR", "Operation failed"]); double.print(); // Heavy borders with custom indentation let mut heavy = Table::new(vec!["Rank", "Player", "Score"]); heavy.set_box_style(BoxStyle::Heavy); heavy.set_indent(5); heavy.set_column_alignment(0, Alignment::Center); heavy.set_column_alignment(2, Alignment::Right); heavy.add_row(vec!["1st", "Alice", "9500"]); heavy.add_row(vec!["2nd", "Bob", "8700"]); heavy.add_row(vec!["3rd", "Charlie", "7200"]); heavy.print(); // ASCII-only borders (for compatibility) let mut ascii = Table::new(vec!["Column A", "Column B"]); ascii.set_box_style(BoxStyle::Ascii); ascii.add_row(vec!["Data 1", "Data 2"]); ascii.add_row(vec!["Data 3", "Data 4"]); ascii.print(); // Unicode-aware: handles emojis and CJK characters correctly let mut unicode = Table::new(vec!["Emoji", "Description", "Width"]); unicode.add_row(vec!["😀", "Grinning face", "2"]); unicode.add_row(vec!["🎉", "Party popper", "2"]); unicode.add_row(vec!["你好", "Hello (Chinese)", "4"]); unicode.print(); } ``` -------------------------------- ### Create Interactive Prompts with zfish Prompt Source: https://github.com/jeetkarena/zfish/blob/main/README.md Implements interactive user prompts for text input, confirmation, and password entry using `zfish::Prompt`. This allows for dynamic user interaction within the CLI. It requires the `zfish` crate. ```rust use zfish::Prompt; fn main() { let name = Prompt::text("What's your name?"); println!("Hello, {}!", name); if Prompt::confirm("Continue?") { println!("Let's go!"); } let password = Prompt::password("Enter password:"); println!("Password length: {}", password.len()); } ``` -------------------------------- ### Safe vs. Unsafe Input Handling in ZFish (Rust) Source: https://github.com/jeetkarena/zfish/blob/main/SECURITY.md Demonstrates how to safely handle user input when styling text with ZFish, preventing potential injection attacks. The safe example sanitizes input by removing escape sequences before applying styling, while the unsafe example shows a direct interpolation that should be avoided. ```rust use zfish::{Style, Color}; // ✅ Safe - controlled styling let user_input = get_user_input(); let sanitized = user_input.replace('\x1b', ""); // Remove escape sequences println!("{}", Style::new().fg(Color::Green).apply(&sanitized)); // ❌ Unsafe - potential injection let user_input = get_user_input(); println!("\x1b[32m{}\x1b[0m", user_input); // DON'T DO THIS ``` -------------------------------- ### Rust CLI App with Nested Subcommands using zfish Source: https://context7.com/jeetkarena/zfish/llms.txt Demonstrates how to define a CLI application with global flags and multiple subcommands ('init', 'build', 'deploy') using the zfish library in Rust. It shows argument parsing, validation, and subcommand matching. Dependencies include the 'zfish' crate. Inputs are command-line arguments, and outputs are console messages indicating the executed action. ```rust use zfish::command::{App, Command, Arg}; fn main() { let app = App::new("myapp") .version("1.0.0") .about("A modern CLI application") // Global flags (apply to all subcommands) .arg(Arg::new("verbose") .short('v') .long("verbose") .about("Enable verbose output")) .arg(Arg::new("config") .short('c') .long("config") .about("Config file path") .default_value("config.toml")) // Subcommand: init .subcommand( Command::new("init") .about("Initialize a new project") .arg(Arg::new("name") .required(true) .about("Project name")) .arg(Arg::new("template") .long("template") .possible_values(&["basic", "advanced", "minimal"]) .default_value("basic")) ) // Subcommand: build .subcommand( Command::new("build") .about("Build the project") .arg(Arg::new("release") .long("release") .about("Build in release mode") .takes_value(false)) .arg(Arg::new("target") .long("target") .about("Target platform") .possible_values(&["x86_64", "arm64", "wasm32"])) .arg(Arg::new("jobs") .short('j') .long("jobs") .default_value("4") .validator(|s| { s.parse::() .map(|_| ()) // Discard the parsed value, just check if it's a number .map_err(|_| "must be a number".to_string()) })) ) // Subcommand: deploy .subcommand( Command::new("deploy") .about("Deploy the application") .arg(Arg::new("environment") .short('e') .long("env") .required(true) .possible_values(&["dev", "staging", "prod"])) .arg(Arg::new("dry-run") .long("dry-run") .takes_value(false)) ); let matches = app.get_matches(); // Access global flags let verbose = matches.is_flag_set("verbose"); let config = matches.value_of("config").unwrap(); if verbose { println!("Using config: {}", config); } // Handle subcommands match matches.subcommand() { Some(("init", sub_matches)) => { let name = sub_matches.value_of("name").unwrap(); let template = sub_matches.value_of("template").unwrap(); println!("Initializing project '{}' with template '{}'", name, template); } Some(("build", sub_matches)) => { let release = sub_matches.is_flag_set("release"); let jobs = sub_matches.value_of("jobs").unwrap(); println!("Building with {} jobs (release: {})", jobs, release); } Some(("deploy", sub_matches)) => { let env = sub_matches.value_of("environment").unwrap(); let dry_run = sub_matches.is_flag_set("dry-run"); println!("Deploying to {} (dry-run: {})", env, dry_run); } _ => println!("No subcommand provided. Use --help for usage."), } } // Usage: // ./myapp --help // ./myapp init myproject --template advanced // ./myapp build --release --jobs 8 // ./myapp deploy --env prod --verbose ``` -------------------------------- ### Display 256-Color Text with zfish Color Source: https://github.com/jeetkarena/zfish/blob/main/README.md Demonstrates the use of `zfish::Color` to display text in 256 different colors. It shows how to use specific custom colors and provides a loop to print all available colors. This requires the `zfish` crate. ```rust use zfish::Color; fn main() { // Use any color from 0-255 println!("{}", Color::Custom(196).paint("Bright red")); println!("{}", Color::Custom(46).paint("Bright green")); println!("{}", Color::Custom(21).paint("Deep blue")); // Show all 256 colors for i in 0..=255 { print!("{} ", Color::Custom(i).paint(format!("{:3}", i))); if (i + 1) % 16 == 0 { println!(); } } } ``` -------------------------------- ### Interactive User Prompts in Rust Source: https://context7.com/jeetkarena/zfish/llms.txt Demonstrates how to collect user input using text, password, and confirmation prompts with the zfish library. It covers basic input, handling passwords securely, and setting default values for confirmations. This functionality is useful for creating interactive command-line applications. ```rust use zfish::Prompt; use std::io; fn main() -> io::Result<()> { // Text input prompt let name = Prompt::text("What's your name?")?; println!("Hello, {}!", name); // Alternative method let email = Prompt::input("Enter your email:")?; println!("Email: {}", email); // Password input (hidden characters) let password = Prompt::password("Enter password:")?; println!("Password length: {} characters", password.len()); // Confirmation prompt with default value let confirmed = Prompt::confirm("Continue with installation?", true)?; if confirmed { println!("Starting installation..."); } else { println!("Installation cancelled"); } // Default false example let delete = Prompt::confirm("Delete all files?", false)?; if delete { println!("Deleting files..."); } else { println!("Operation cancelled"); } // Interactive setup wizard example println!("\n=== Setup Wizard ==="); let project_name = Prompt::text("Project name:")?; let use_git = Prompt::confirm("Initialize git repository?", true)?; let use_ci = Prompt::confirm("Enable CI/CD?", false)?; println!("\nConfiguration:"); println!(" Name: {}", project_name); println!(" Git: {}", if use_git { "Yes" } else { "No" }); println!(" CI/CD: {}", if use_ci { "Yes" } else { "No" }); Ok(()) } ``` -------------------------------- ### Basic Styling and Colors in Zfish Source: https://github.com/jeetkarena/zfish/blob/main/README.md Demonstrates the use of 16 ANSI colors and text styling (bold, italic, etc.) within the zfish framework. This module allows for visually rich terminal output. No external dependencies are required beyond the standard library. ```Rust use zfish::style::{Style, Color}; fn main() { println!("{}", Style::Bold.paint("This is bold text")); println!("{}", Color::Red.paint("This is red text")); println!("{}", Style::Italic.paint("This is italic")); // Example of chaining styles println!("{}", Style::Bold.append(Style::Italic).paint("Bold and Italic")); // Example of 256-color palette println!("{}", Color::Custom(196).paint("Custom Color (196)")); } ``` -------------------------------- ### Argument Parsing with Flags, Options, and Subcommands in Zfish Source: https://github.com/jeetkarena/zfish/blob/main/README.md Illustrates how to define and parse command-line arguments using zfish. Supports flags, options with values, positional arguments, and a git-style subcommand system. Includes auto-generated help messages and validation. ```Rust use zfish::args::{Args, Positional}; use zfish::command::Command; fn main() { let mut cmd = Command::new("my_cli"); cmd.add_subcommand("greet", |cmd| { cmd.add_arg(Args::new("--name", "Your name").required(true)); cmd.add_arg(Args::new("-c, --count", "Number of greetings").default("1")); }); let matches = cmd.run().unwrap_or_else(|e| { eprintln!("Error: {}", e); std::process::exit(1); }); if let Some(subcommand) = matches.subcommand() { match subcommand.name() { "greet" => { let name = subcommand.value_of("name").unwrap(); let count = subcommand.value_of("count").unwrap().parse::().unwrap(); for _ in 0..count { println!("Hello, {}!", name); } } _ => unreachable!(), } } else { // Handle cases with no subcommand or display help println!("{}", cmd.help_text()); } } ``` -------------------------------- ### Complete CLI Application using zfish in Rust Source: https://context7.com/jeetkarena/zfish/llms.txt This Rust code demonstrates a full CLI application built with zfish. It includes argument parsing for options like verbosity and iterations, a custom logger with different levels, a progress bar for long-running tasks, and styled terminal output for user feedback and help messages. It relies on the 'zfish' crate for all its functionality. ```rust use zfish::{Args, Color, Style, Logger, Level, ProgressBar, Terminal}; use std::thread; use std::time::Duration; fn main() { let args = Args::parse(); // Setup logger let log_level = if args.has_flag("verbose") || args.has_flag("v") { Level::Debug } else { Level::Info }; let logger = Logger::new().level(log_level); // Show help if args.has_flag("help") || args.has_flag("h") { show_help(); return; } // Parse configuration let iterations = args .get_option("iterations") .and_then(|s| s.parse::().ok()) .unwrap_or(50); let output_file = args .get_option("output") .map(|s| s.as_str()) .unwrap_or("output.txt"); // Application header Terminal::clear_screen().ok(); println!("{}", Color::Cyan.paint("╔════════════════════════════════╗").style(Style::Bold)); println!("{}", Color::Cyan.paint("║ My Awesome CLI Application ║").style(Style::Bold)); println!("{}", Color::Cyan.paint("╚════════════════════════════════╝").style(Style::Bold)); println!(); // Start processing logger.info(&format!("{}", Color::Green.paint("Starting application..."))); logger.debug(&format!("Iterations: {}", iterations)); logger.debug(&format!("Output file: {}", output_file)); // Show progress logger.info("Processing data..."); let mut pb = ProgressBar::new(iterations); for i in 0..iterations { thread::sleep(Duration::from_millis(50)); if i % 10 == 0 { logger.debug(&format!("Processed {} items", i)); } pb.set(i + 1); } pb.finish(&format!("{}", Color::Green.paint("✓ Processing complete!"))); // Summary logger.info(&format!("Results saved to: {}", Color::Cyan.paint(output_file))); logger.info(&format!("{}", Color::Green.paint("✓ Done!").style(Style::Bold))); println!("\n{}", Color::Magenta.paint("=== Summary ===").style(Style::Bold)); println!(" Processed: {} items", iterations); println!(" Output: {}", output_file); println!(" Status: {}", Color::Green.paint("Success")); } fn show_help() { println!("{}", Color::Cyan.paint("My CLI Tool").style(Style::Bold)); println!(); println!("USAGE:"); println!(" myapp [OPTIONS]"); println!(); println!("OPTIONS:"); println!(" -h, --help Show help information"); println!(" -v, --verbose Enable verbose logging"); println!(" --iterations Number of iterations [default: 50]"); println!(" -o, --output Output file path [default: output.txt]"); println!(); println!("EXAMPLES:"); println!(" myapp --iterations 100"); println!(" myapp --verbose -o results.txt"); } // Run with: // cargo run -- --help // cargo run -- --verbose --iterations 30 // cargo run -- -o myfile.txt ``` -------------------------------- ### Interactive Prompts (Text, Password, Confirmation) in Zfish Source: https://github.com/jeetkarena/zfish/blob/main/README.md Demonstrates how to create interactive command-line prompts for user input, including plain text, password entry (hidden input), and yes/no confirmations. This module is useful for gathering user preferences or validating input during runtime. ```Rust use zfish::prompt::{Prompt, Confirm, Password}; fn main() { let name = Prompt::text("What is your name?").interact().unwrap(); println!("Hello, {}!", name); let should_proceed = Confirm::new("Do you want to continue?").interact().unwrap(); if should_proceed { println!("Continuing..."); } else { println!("Aborting."); return; } let password = Password::new("Enter your secret password:").interact().unwrap(); println!("Password received (hidden)."); } ``` -------------------------------- ### Leveled Logging with zfish Source: https://context7.com/jeetkarena/zfish/llms.txt This Rust code demonstrates how to use the zfish Logger for outputting messages at different severity levels. It covers creating a logger with default and custom levels, showing how messages below the set level are filtered out. The output format includes timestamps and severity levels, with automatic colorization for each level. Dependencies include the `zfish` crate. ```rust use zfish::{Logger, Level, Color}; fn main() { // Create logger with default level (Info) let logger = Logger::new(); logger.error("Failed to connect to database"); logger.warn("Configuration file not found, using defaults"); logger.info("Application started successfully"); logger.debug("Cache hit for key 'user:123'"); // Not shown (below Info) // Create logger with custom level let debug_logger = Logger::new().level(Level::Debug); debug_logger.error("Critical error occurred"); debug_logger.warn("Deprecated API usage detected"); debug_logger.info("Processing request #1234"); debug_logger.debug("Executing query: SELECT * FROM users"); // Log levels in order of priority: // Error > Warn > Info > Debug // Example application logging let app_logger = Logger::new().level(Level::Info); app_logger.info("Starting server on port 8080"); if let Err(e) = start_server() { app_logger.error(&format!("Server failed to start: {}", e)); } else { app_logger.info("Server running"); } app_logger.info("Processing 1000 items"); for i in 0..1000 { if i % 100 == 0 { app_logger.debug(&format!("Processed {} items", i)); } } app_logger.info("Processing complete"); // Output format: [timestamp] LEVEL message // [1705392847] ERROR Failed to connect to database // [1705392847] WARN Configuration file not found, using defaults // [1705392847] INFO Application started successfully // Colors are automatically applied: // ERROR - Bright Red // WARN - Bright Yellow // INFO - Bright Blue // DEBUG - Bright Black/Gray } fn start_server() -> Result<(), String> { Ok(()) } ``` -------------------------------- ### Command Aliases Source: https://github.com/jeetkarena/zfish/blob/main/V0.2.1_IMPLEMENTATION_SUMMARY.md Creates alternative names for commands using `.alias()`. Allows users to invoke the same command with shorter or alternative names like `init` for `initialize`. ```rust Command::new("initialize") .alias("init") .alias("i") ``` -------------------------------- ### Apply Terminal Color Styling with 256-Color Support Source: https://context7.com/jeetkarena/zfish/llms.txt Style terminal output with 16 ANSI colors, bright variants, and a 256-color palette. Combine multiple text styles (bold, underline) and automatically respect the NO_COLOR environment variable for accessibility. ```rust use zfish::{Color, Style}; fn main() { // Standard ANSI colors println!("{}", Color::Red.paint("Error: Operation failed")); println!("{}", Color::Green.paint("✓ Success!")); println!("{}", Color::Yellow.paint("⚠ Warning")); println!("{}", Color::Blue.paint("Info message")); // Bright color variants println!("{}", Color::BrightRed.paint("Critical error")); println!("{}", Color::BrightGreen.paint("All tests passed")); // 256-color palette (0-255) println!("{}", Color::Custom(196).paint("Bright red (196)")); println!("{}", Color::Custom(46).paint("Bright green (46)")); println!("{}", Color::Custom(21).paint("Deep blue (21)")); // Combine colors with text styles let styled = Color::Red.paint("Bold Error").style(Style::Bold); println!("{}", styled); let fancy = Color::Cyan.paint("Title") .style(Style::Bold) .style(Style::Underline); println!("{}", fancy); // Display all 256 colors for i in 0..=255 { print!("{} ", Color::Custom(i).paint(format!("{:3}", i))); if (i + 1) % 16 == 0 { println!(); } } // Respects NO_COLOR environment variable automatically // Colors disabled when NO_COLOR is set } ``` -------------------------------- ### Comprehensive Test Suite for Command Features (Rust) Source: https://github.com/jeetkarena/zfish/blob/main/V0.2.1_IMPLEMENTATION_SUMMARY.md A collection of unit tests designed to cover all implemented argument parsing features, including positive cases, edge cases, and known limitations. Ensures robustness and reliability. ```rust // tests/test_command_v2_features.rs // Contains 27 comprehensive tests covering positional args, env var fallbacks, conflicts, etc. ``` -------------------------------- ### Progress Bar and Spinner Styles in Zfish Source: https://github.com/jeetkarena/zfish/blob/main/README.md Shows how to implement progress indicators using different styles like bars, spinners, dots, and arrows. This module enhances user experience by providing visual feedback on long-running operations. Custom width can also be set. ```Rust use zfish::progress::{Progress, Spinner, Dots}; use std::thread::sleep; use std::time::Duration; fn main() { // Example with a classic progress bar let mut progress = Progress::new(100); for i in 0..100 { progress.set(i); sleep(Duration::from_millis(50)); } progress.finish_with_message("Done!"); // Example with a spinner let mut spinner = Spinner::new(); spinner.start("Processing..."); sleep(Duration::from_secs(3)); spinner.stop("Completed."); // Example with dots let mut dots = Dots::new(); dots.start("Loading"); sleep(Duration::from_secs(3)); dots.stop("Loaded."); } ``` -------------------------------- ### Table Rendering with Box Styles and Column Alignment in Zfish Source: https://github.com/jeetkarena/zfish/blob/main/README.md Explains how to generate formatted tables in the terminal using zfish. Supports multiple box drawing styles (Single, Double, Heavy, Rounded, ASCII), column alignment (Left, Right, Center), and Unicode-aware width calculation for proper rendering of complex characters. ```Rust use zfish::table::{Table, Style as TableStyle, Alignment}; fn main() { let mut table = Table::new(TableStyle::Rounded); table.set_header(&["ID", "Name", "Role"]); table.add_row(&["1", "Alice", "Developer"]); table.add_row(&["2", "Bob", "Designer"]); table.add_row(&["3", "Charlie", "Manager"]); // Set column alignments table.set_column_alignment(0, Alignment::Center); table.set_column_alignment(2, Alignment::Right); println!("{}", table); } ``` -------------------------------- ### Cargo Test Suite Execution Source: https://github.com/jeetkarena/zfish/blob/main/V0.2.1_IMPLEMENTATION_SUMMARY.md Executes all tests in the project. Results show 67+ tests passed with zero failures, indicating comprehensive test coverage. ```bash cargo test # Result: 67+ tests passed, 0 failed ✅ ``` -------------------------------- ### Terminal Manipulation with zfish Source: https://context7.com/jeetkarena/zfish/llms.txt This Rust code snippet demonstrates various terminal control functionalities provided by the zfish crate. It includes clearing the screen, moving the cursor to specific coordinates, printing text at given positions, detecting terminal dimensions, drawing a border, and creating an animated loading indicator. The code requires the `zfish` crate and standard Rust libraries for I/O and threading. Error handling for terminal operations is included. ```rust use zfish::Terminal; use std::io; use std::thread; use std::time::Duration; fn main() -> io::Result<()> { // Clear entire screen Terminal::clear_screen()?; // Move cursor to specific position (row, col) Terminal::move_cursor(1, 1)?; println!("Top-left corner"); Terminal::move_cursor(10, 20)?; println!("Row 10, Column 20"); // Print text at specific position Terminal::print_at(5, 10, "Hello, World!")?; Terminal::print_at(6, 10, "This is line 2")?; Terminal::print_at(7, 10, "This is line 3")?; // Get terminal dimensions if let Some((width, height)) = Terminal::size() { Terminal::print_at(15, 1, &format!("Terminal size: {}x{}", width, height))?; // Draw a border around terminal for col in 1..=width { Terminal::print_at(1, col, "─")?; Terminal::print_at(height, col, "─")?; } for row in 1..=height { Terminal::print_at(row, 1, "│")?; Terminal::print_at(row, width, "│")?; } } // Animated loading indicator Terminal::clear_screen()?; let frames = vec!["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; for _ in 0..50 { for frame in &frames { Terminal::print_at(10, 40, &format!("{} Loading...", frame))?; thread::sleep(Duration::from_millis(80)); } } Terminal::print_at(10, 40, "✓ Done! ")?; Terminal::move_cursor(20, 1)?; Ok(()) } ``` -------------------------------- ### Terminal Control: Clear Screen, Cursor Movement, and Size in Zfish Source: https://github.com/jeetkarena/zfish/blob/main/README.md Demonstrates various terminal control functionalities provided by zfish, including clearing the screen, moving the cursor to specific positions, and detecting the terminal's dimensions. These features enable dynamic and interactive terminal UIs. ```Rust use zfish::term::{Terminal, Size}; fn main() { // Clear the terminal screen Terminal::clear_screen(); // Get terminal size match Terminal::size() { Ok(Size { rows, cols }) => { println!("Terminal size: {} rows, {} cols", rows, cols); // Print text at a specific position Terminal::print_at(rows / 2, cols / 2, "Hello at center!").unwrap(); } Err(e) => { eprintln!("Could not get terminal size: {}", e); } } // Move cursor up by 1 row Terminal::move_cursor(-1, 0).unwrap(); } ``` -------------------------------- ### Display Progress Bars with Multiple Styles Source: https://context7.com/jeetkarena/zfish/llms.txt Create animated progress bars with multiple visual styles (classic, spinner, arrow, dots) that display percentage, current/total count, items per second, and estimated time remaining. Supports custom width and real-time updates. ```rust use zfish::{ProgressBar, ProgressStyle}; use std::thread; use std::time::Duration; fn main() { // Classic progress bar style let mut pb = ProgressBar::new(100); for i in 0..=100 { pb.set(i); thread::sleep(Duration::from_millis(50)); } pb.finish("✓ Download complete!"); // Custom width and style let mut spinner = ProgressBar::new(50) .width(60) .with_style(ProgressStyle::Spinner); for i in 0..=50 { spinner.inc(1); thread::sleep(Duration::from_millis(100)); } spinner.finish("✓ Processing finished!"); // Arrow style progress bar let mut arrow_bar = ProgressBar::new(200) .with_style(ProgressStyle::Arrow); for i in 0..=200 { arrow_bar.set(i); thread::sleep(Duration::from_millis(25)); } arrow_bar.finish("✓ Upload complete!"); // Dots style (alternative visual) let mut dots = ProgressBar::new(75) .with_style(ProgressStyle::Dots); for i in 0..=75 { dots.set(i); thread::sleep(Duration::from_millis(30)); } dots.finish("✓ Task completed!"); // Progress bar shows: percentage, current/total, items/sec, ETA // Output: [=========> ] 45.0% (45/100) 10.2/s ETA: 5.4s } ``` -------------------------------- ### Parse Command-Line Arguments with zfish Args Source: https://github.com/jeetkarena/zfish/blob/main/README.md Parses command-line arguments using the `zfish::Args` struct. It demonstrates how to check for flags, retrieve option values, and iterate over positional arguments. No external dependencies beyond the `zfish` crate are required. ```rust use zfish::Args; fn main() { let args = Args::parse(); if args.has_flag("verbose") || args.has_flag("v") { println!("Verbose mode enabled"); } if let Some(file) = args.get_option("file") { println!("Processing: {}", file); } for arg in &args.positional { println!("Positional argument: {}", arg); } } ``` -------------------------------- ### ZFish Project Information Banner Source: https://github.com/jeetkarena/zfish/blob/main/README.md A stylized text banner displaying core project information for ZFish v0.1.10, including the copyright year and licensing information (MIT License). This banner is typically found at the end of documentation or in a project's README. ```text ╔═══════════════════════════════════════════════════════════════╗ ║ zfish v0.1.10 ║ ║ Copyright © 2025 Jeet Karena ║ ║ Licensed under MIT License ║ ╚═══════════════════════════════════════════════════════════════╝ ``` -------------------------------- ### Cargo Clippy Linting Source: https://github.com/jeetkarena/zfish/blob/main/V0.2.1_IMPLEMENTATION_SUMMARY.md Runs Clippy with strict warnings-as-errors flag to ensure code quality and best practices. Returns zero warnings and zero errors. ```bash cargo clippy -- -D warnings # Result: 0 warnings, 0 errors ✅ ```