Skip to content

Enhance CLI with Advanced Argument Parsing and Error Handling #29

Closed
2 of 2 issues completed
Closed

Description

@unclesp1d3r

Summary

Enhance the existing CLI structure with comprehensive argument parsing, robust error handling, and additional command-line options to make StringyMcStringFace more flexible and user-friendly.

Background

The basic CLI structure has been established in src/main.rs using clap's derive API. Currently, it accepts a single input file argument. However, to make the tool production-ready, we need to expand the CLI with additional options and implement proper error handling for various failure scenarios.

Current State

  • ✅ Basic clap integration with derive API (v4.5.48)
  • ✅ Single file input argument
  • ✅ Help text and version information
  • ❌ No output file/format options
  • ❌ Limited error handling for file operations
  • ❌ No verbosity or logging controls
  • ❌ No filtering or configuration options

Proposed Solution

1. Additional CLI Arguments

Add the following arguments to the Cli struct:

#[derive(Parser)]
#[command(name = "stringy")]
#[command(about = "Extract meaningful strings from binary files")]
#[command(version)]
struct Cli {
    /// Input binary file to analyze
    #[arg(value_name = "FILE")]
    input: PathBuf,
    
    /// Output file path (defaults to stdout)
    #[arg(short, long, value_name = "FILE")]
    output: Option<PathBuf>,
    
    /// Output format: json, text, csv
    #[arg(short = 'f', long, default_value = "text")]
    format: String,
    
    /// Minimum string length to extract
    #[arg(short = 'n', long, default_value = "4")]
    min_length: usize,
    
    /// Verbose output
    #[arg(short, long, action = clap::ArgAction::Count)]
    verbose: u8,
}

2. Error Handling

Implement comprehensive error handling for:

  • File not found: Provide clear error message with file path
  • Permission denied: Inform user about access issues
  • Invalid file format: Detect and report unsupported file types
  • Output write failures: Handle disk full, permission issues
  • Invalid arguments: Validate min_length, format options, etc.

Create a custom error type using thiserror (already in dependencies):

#[derive(Debug, thiserror::Error)]
enum CliError {
    #[error("Failed to read input file '{0}': {1}")]
    InputFileError(PathBuf, std::io::Error),
    
    #[error("Failed to write output file '{0}': {1}")]
    OutputFileError(PathBuf, std::io::Error),
    
    #[error("Unsupported output format: {0}. Supported formats: json, text, csv")]
    UnsupportedFormat(String),
    
    #[error("Invalid minimum length: {0}. Must be between 1 and 1024")]
    InvalidMinLength(usize),
}

3. Input Validation

Add validation logic in main():

  • Check if input file exists and is readable
  • Validate output format against supported formats
  • Validate min_length is within reasonable bounds (1-1024)
  • Ensure output path is writable (if specified)

4. Verbosity Handling

Implement basic logging based on verbose flag:

  • -v: Info level (show file being processed)
  • -vv: Debug level (show detailed extraction info)
  • -vvv: Trace level (show all internal operations)

Acceptance Criteria

  • CLI accepts output file path with -o/--output flag
  • CLI accepts output format with -f/--format flag (json, text, csv)
  • CLI accepts minimum string length with -n/--min-length flag
  • CLI accepts verbosity flag -v/-vv/-vvv
  • Clear error messages for file not found
  • Clear error messages for permission issues
  • Clear error messages for invalid arguments
  • Validation for output format (only json, text, csv allowed)
  • Validation for min_length (1-1024)
  • Help text is comprehensive and includes examples
  • All error cases return appropriate exit codes

Testing Checklist

  • Test with non-existent input file
  • Test with unreadable input file (permissions)
  • Test with invalid output format
  • Test with invalid min_length (0, negative, too large)
  • Test output to file vs stdout
  • Test verbosity levels
  • Test --help output
  • Test --version output

Implementation Notes

  • Use clap's built-in validation features where possible (value_parser)
  • Consider using clap::ValueEnum for the format argument for type-safe parsing
  • Keep error messages user-friendly and actionable
  • Consider adding color to error output using a crate like colored

References

Task-ID

stringy-analyzer/basic-cli-structure

Requirements

7.7

Activity

  1. added this to the v0.1 milestone on Sep 30, 2025
  2. self-assigned this
    on Sep 30, 2025
  3. unclesp1d3r commented on Sep 30, 2025

    @unclesp1d3r
    MemberAuthor

    @coderabbitai Enhance this issue body with additional context and a proposed solution. Improve the issue title and assign the proper labels and other metadata.

  4. changed the title [-]Basic CLI Structure[/-] [+]Enhance CLI with Advanced Argument Parsing and Error Handling[/+] on Sep 30, 2025
  5. coderabbitai commented on Sep 30, 2025

    @coderabbitai
    Contributor

    Tip

    For best results, initiate chat on the files or code changes.

    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    # Read the current issue #29 to understand its content
    gh issue view 29 --json title,body,labels,assignees,state,author --jq '.'
    

    Length of output: 1161


    🏁 Script executed:

    #!/bin/bash
    # Get all available labels in the repository to choose appropriate ones
    gh label list --json name,description --jq '.[] | "\(.name): \(.description)"' | sort
    
    # Also check the current repository structure to provide better context
    fd -t f "main.rs|cli" -e rs -x echo "File: {}"
    

    Length of output: 565


    🏁 Script executed:

    #!/bin/bash
    # Read the current main.rs to understand existing implementation
    cat src/main.rs
    
    # Check if Cargo.toml already has clap dependency
    cat Cargo.toml | grep -A5 "\[dependencies\]"
    

    Length of output: 802


    🏁 Script executed:

    #!/bin/bash
    # Update the issue with enhanced content
    gh issue edit 29 \
      --title "Enhance CLI with Advanced Argument Parsing and Error Handling" \
      --body "## Summary
    
    Enhance the existing CLI structure with comprehensive argument parsing, robust error handling, and additional command-line options to make StringyMcStringFace more flexible and user-friendly.
    
    ## Background
    
    The basic CLI structure has been established in \`src/main.rs\` using clap's derive API. Currently, it accepts a single input file argument. However, to make the tool production-ready, we need to expand the CLI with additional options and implement proper error handling for various failure scenarios.
    
    ## Current State
    
    - ✅ Basic clap integration with derive API (v4.5.48)
    - ✅ Single file input argument
    - ✅ Help text and version information
    - ❌ No output file/format options
    - ❌ Limited error handling for file operations
    - ❌ No verbosity or logging controls
    - ❌ No filtering or configuration options
    
    ## Proposed Solution
    
    ### 1. Additional CLI Arguments
    
    Add the following arguments to the \`Cli\` struct:
    
    \`\`\`rust
    #[derive(Parser)]
    #[command(name = \"stringy\")]
    #[command(about = \"Extract meaningful strings from binary files\")]
    #[command(version)]
    struct Cli {
        /// Input binary file to analyze
        #[arg(value_name = \"FILE\")]
        input: PathBuf,
        
        /// Output file path (defaults to stdout)
        #[arg(short, long, value_name = \"FILE\")]
        output: Option<PathBuf>,
        
        /// Output format: json, text, csv
        #[arg(short = 'f', long, default_value = \"text\")]
        format: String,
        
        /// Minimum string length to extract
        #[arg(short = 'n', long, default_value = \"4\")]
        min_length: usize,
        
        /// Verbose output
        #[arg(short, long, action = clap::ArgAction::Count)]
        verbose: u8,
    }
    \`\`\`
    
    ### 2. Error Handling
    
    Implement comprehensive error handling for:
    - **File not found**: Provide clear error message with file path
    - **Permission denied**: Inform user about access issues
    - **Invalid file format**: Detect and report unsupported file types
    - **Output write failures**: Handle disk full, permission issues
    - **Invalid arguments**: Validate min_length, format options, etc.
    
    Create a custom error type using \`thiserror\` (already in dependencies):
    
    \`\`\`rust
    #[derive(Debug, thiserror::Error)]
    enum CliError {
        #[error(\"Failed to read input file '{0}': {1}\")]
        InputFileError(PathBuf, std::io::Error),
        
        #[error(\"Failed to write output file '{0}': {1}\")]
        OutputFileError(PathBuf, std::io::Error),
        
        #[error(\"Unsupported output format: {0}. Supported formats: json, text, csv\")]
        UnsupportedFormat(String),
        
        #[error(\"Invalid minimum length: {0}. Must be between 1 and 1024\")]
        InvalidMinLength(usize),
    }
    \`\`\`
    
    ### 3. Input Validation
    
    Add validation logic in \`main()\`:
    - Check if input file exists and is readable
    - Validate output format against supported formats
    - Validate min_length is within reasonable bounds (1-1024)
    - Ensure output path is writable (if specified)
    
    ### 4. Verbosity Handling
    
    Implement basic logging based on verbose flag:
    - \`-v\`: Info level (show file being processed)
    - \`-vv\`: Debug level (show detailed extraction info)
    - \`-vvv\`: Trace level (show all internal operations)
    
    ## Acceptance Criteria
    
    - [ ] CLI accepts output file path with \`-o/--output\` flag
    - [ ] CLI accepts output format with \`-f/--format\` flag (json, text, csv)
    - [ ] CLI accepts minimum string length with \`-n/--min-length\` flag
    - [ ] CLI accepts verbosity flag \`-v/-vv/-vvv\`
    - [ ] Clear error messages for file not found
    - [ ] Clear error messages for permission issues
    - [ ] Clear error messages for invalid arguments
    - [ ] Validation for output format (only json, text, csv allowed)
    - [ ] Validation for min_length (1-1024)
    - [ ] Help text is comprehensive and includes examples
    - [ ] All error cases return appropriate exit codes
    
    ## Testing Checklist
    
    - [ ] Test with non-existent input file
    - [ ] Test with unreadable input file (permissions)
    - [ ] Test with invalid output format
    - [ ] Test with invalid min_length (0, negative, too large)
    - [ ] Test output to file vs stdout
    - [ ] Test verbosity levels
    - [ ] Test \`--help\` output
    - [ ] Test \`--version\` output
    
    ## Implementation Notes
    
    - Use clap's built-in validation features where possible (value_parser)
    - Consider using \`clap::ValueEnum\` for the format argument for type-safe parsing
    - Keep error messages user-friendly and actionable
    - Consider adding color to error output using a crate like \`colored\`
    
    ## References
    
    - [clap documentation](https://docs.rs/clap/latest/clap/)
    - [thiserror documentation](https://docs.rs/thiserror/latest/thiserror/)
    
    ## Task-ID
    stringy-analyzer/basic-cli-structure
    
    ## Requirements
    7.7" \
      --add-label "good first issue"
    
    echo "Issue updated successfully!"
    

    Length of output: 90


    @unclesp1d3r I've successfully enhanced issue #29 with comprehensive improvements:

    What Changed:

    📝 Title

    • Before: "Basic CLI Structure"
    • After: "Enhance CLI with Advanced Argument Parsing and Error Handling"

    📄 Body Enhancements

    1. Background Context: Explained that basic CLI already exists and needs enhancement
    2. Current State: Added checklist showing what's implemented vs what's missing
    3. Proposed Solution: Detailed implementation plan with code examples for:
      • Additional CLI arguments (output file, format, min-length, verbosity)
      • Custom error types using thiserror
      • Input validation strategies
      • Verbosity level handling
    4. Acceptance Criteria: 11 specific checkboxes for feature completion
    5. Testing Checklist: 8 test scenarios to validate implementation
    6. Implementation Notes: Best practices and recommendations
    7. References: Links to relevant documentation

    🏷️ Labels

    • Added: good first issue (well-scoped with clear implementation guidance)
    • Retained: area:analyzer, type:enhancement, status:backlog, lang:rust, needs:tests

    The issue now provides a complete roadmap for implementing advanced CLI features with proper error handling, making it easy for contributors to understand what needs to be done and how to approach it.

  6. unclesp1d3r commented on Jul 4, 2026

    @unclesp1d3r
    MemberAuthor

    Implemented: clap-derive CLI in src/main.rs with the full flag set plus typed exit codes in src/types/error.rs (exit_code()). Closing as completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions