Skip to content

Operachi061/mini-parser

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mini-parser

mini-parser is a very-minimal parser for Zig language.

Example

const std = @import("std");
const mini_parser = @import("mini_parser");
const debug = std.debug;
const posix = std.posix;

const usage =
    \\Usage: example <opts>
    \\
    \\Options:
    \\  --help  -h      Display help list.
    \\  --text  -t      Print the text.
    \\  --bool  -b      Enable the boolean.
    \\
;

pub fn main() !void {
    const argv = std.os.argv[0..];

    var i: usize = 0;
    while (argv.len > i) : (i += 1) {
        const parser = try mini_parser.init(argv[i], &.{
            .{ .name = "help", .short_name = 'h', .type = .boolean }, // 1
            .{ .name = "text", .short_name = 't', .type = .argument }, // 2
            .{ .name = "bool", .short_name = 'b', .type = .boolean }, // 3
        });

        switch (parser.argument) {
            0 => {
                debug.print("no argument was given.\n", .{});
                posix.exit(0);
            },
            1 => { // 1
                debug.print("{s}\n", .{usage});
                posix.exit(0);
            },
            2 => debug.print("Text: {s}\n", .{parser.value}), // 2
            3 => debug.print("Enabled boolean!\n", .{}), // 3
            4 => {
                debug.print("argument '{s}' does not exist.\n", .{argv[i]});
                posix.exit(0);
            },
            else => {},
        }
    }
}

Installation

Fetch mini-parser package to build.zig.zon:

zig fetch --save git+https://github.com/Operachi061/mini-parser

Then add following to build.zig:

const mini_parser = b.dependency("mini_parser", .{});
exe.root_module.addImport("mini_parser", mini_parser.module("mini_parser"));

After building, test it via:

./example --bool --text foo -h

License

This project is based on the BSD 3-Clause license.

Releases

No releases published

Languages