zargs/examples/README.md

2.1 KiB

File Processor Example

A practical example demonstrating the new lazy parsing API for zargs.

Building

zig build examples

Running

Show help:

zig build run-file-processor -- --help

Basic usage with defaults:

zig build run-file-processor

With verbose output:

zig build run-file-processor -- -v

Full example with all options:

zig build run-file-processor -- \
  --input=data.csv \
  --output=result.json \
  --format=xml \
  --max-size=2048 \
  --tags=important,urgent,reviewed \
  --verbose

Short flags:

zig build run-file-processor -- -i data.csv -o result.json -f json -m 512 -t alpha,beta -v

Features Demonstrated

  1. Boolean flags: --verbose / -v
  2. String arguments: --input / -i, --output / -o
  3. Integer arguments: --max-size / -m
  4. Enum arguments: --format / -f (json, xml, csv)
  5. String lists: --tags / -t (comma-separated)
  6. Help text: --help / -h
  7. Default values: All arguments have sensible defaults

Code Structure

const Config = struct {
    // Define your configuration fields
    input: []const u8 = "input.txt",
    verbose: bool = false,
    format: Format = .json,
    
    // Define metadata for help text and short flags
    pub const meta = .{
        .input = .{ .short = 'i', .help = "Input file path" },
        .verbose = .{ .short = 'v', .help = "Enable verbose output" },
        .format = .{ .short = 'f', .help = "Output format" },
    };
};

// Parse in one line!
const config = try parse.parse(Config, allocator, argv);

Memory Model

This example uses the arena allocator pattern where all parsed strings live until program exit. This is appropriate for command-line applications where:

  • Arguments are parsed once at startup
  • Values are used throughout the program lifetime
  • No need for complex lifetime management

Notes

  • The "memory address leaked" messages in GPA output are expected and safe
  • The arena allocator manages all string lifetimes automatically
  • Unknown arguments are silently ignored (multi-module friendly)