simargs

A simple, opinionated, struct-based argument parser in Zig, taking full advantage of comptime.

Features

  • Supported data type:

  • Optional fields and fields with default value mean they are optional arguments
  • Use comptime as possible as I can
  • Provide printHelp() out of the box
  • Support sub commands

Usage

See simargs-demo.zig.

1
2
# Run demo
zig build run-simargs-demo -- -o /tmp/a.out --user-agent Firefox sub1 --a 123 hello world 2>&1
------------------------------Program------------------------------
/Users/jiacai/gh/zigcli/.zig-cache/o/bd8a4fb104779110e787d579f1d9c6f0/simargs-demo

------------------------------Arguments------------------------------
   verbose: null
user-agent: simargs-demo.main__struct_1700.main__struct_1700__enum_1707.Firefox
   timeout: 30
    output: /tmp/a.out
      help: false
__commands__: simargs-demo.main__struct_1700.main__struct_1700__union_1708{ .sub1 = simargs-demo.main__struct_1700.main__struct_1700__union_1708.main__struct_1700__union_1708__struct_1710{ .a = 123, .help = false } }

------------------------------Positionals------------------------------
1: hello
2: world

------------------------------print_help------------------------------
 USAGE:
     /Users/jiacai/gh/zigcli/.zig-cache/o/bd8a4fb104779110e787d579f1d9c6f0/simargs-demo [OPTIONS] [COMMANDS]

 COMMANDS:
  sub1       Subcommand 1
  sub2       Subcommand 2

 OPTIONS:
  -v, --verbose                    Make the operation more talkative
  -A, --user-agent STRING           (valid: Chrome|Firefox|Safari)(default: Firefox)
      --timeout INTEGER            Max time this request can cost(default: 30)
  -o, --output STRING              Write to file instead of stdout(required)
  -h, --help

Acknowledgment

Blog post explaining how simargs is implemented: What I learn by implementing argparser in Zig.

When implement simargs, I refer following projects to learn how to write idiomatic Zig code. Big Thanks!

Last modified September 28, 2024: refactor zip file directory structure (9e01903)