Initial commit

This commit is contained in:
Cameron Reed 2024-07-15 19:14:46 -06:00
commit cf88d546cd
6 changed files with 607 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.zig-cache/
zig-out/

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Cameron Reed
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

91
build.zig Normal file
View File

@ -0,0 +1,91 @@
const std = @import("std");
// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const lib = b.addStaticLibrary(.{
.name = "zig-args",
// In this case the main source file is merely a path, however, in more
// complicated build scripts, this could be a generated file.
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
});
// This declares intent for the library to be installed into the standard
// location when the user invokes the "install" step (the default step when
// running `zig build`).
b.installArtifact(lib);
const exe = b.addExecutable(.{
.name = "zig-args-test",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
// step when running `zig build`).
b.installArtifact(exe);
// This *creates* a Run step in the build graph, to be executed when another
// step is evaluated that depends on it. The next line below will establish
// such a dependency.
const run_cmd = b.addRunArtifact(exe);
// By making the run step depend on the install step, it will be run from the
// installation directory rather than directly from within the cache directory.
// This is not necessary, however, if the application depends on other installed
// files, this ensures they will be present and in the expected location.
run_cmd.step.dependOn(b.getInstallStep());
// This allows the user to pass arguments to the application in the build
// command itself, like this: `zig build run -- arg1 arg2 etc`
if (b.args) |args| {
run_cmd.addArgs(args);
}
// This creates a build step. It will be visible in the `zig build --help` menu,
// and can be selected like this: `zig build run`
// This will evaluate the `run` step rather than the default, which is "install".
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
// Creates a step for unit testing. This only builds the test executable
// but does not run it.
const lib_unit_tests = b.addTest(.{
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
});
const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);
const exe_unit_tests = b.addTest(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
// Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request
// running the unit tests.
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_lib_unit_tests.step);
test_step.dependOn(&run_exe_unit_tests.step);
}

72
build.zig.zon Normal file
View File

@ -0,0 +1,72 @@
.{
// This is the default name used by packages depending on this one. For
// example, when a user runs `zig fetch --save <url>`, this field is used
// as the key in the `dependencies` table. Although the user can choose a
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = "zig-argument-parser",
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package. Only files listed here will remain on disk
// when using the zig package manager. As a rule of thumb, one should list
// files required for compilation plus any license(s).
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}

34
src/main.zig Normal file
View File

@ -0,0 +1,34 @@
const std = @import("std");
const arguments = @import("root.zig");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var first = arguments.IntArgument.init(&[_][]const u8{"first"}, &[_]u8{'f'}, 0);
var second = arguments.StringArgument.init(&[_][]const u8{"second"}, &[_]u8{'s'}, "");
var third = arguments.BoolArgument.init(&[_][]const u8{"third"}, &[_]u8{'t'});
var fourth = arguments.BoolArgument.init(&[_][]const u8{"fourth"}, &[_]u8{'x'});
var name = arguments.PositionalStringArgument.init("", true);
var age = arguments.PositionalIntArgument.init(0, true);
var optional = arguments.PositionalStringArgument.init("", false);
var args = [_]*arguments.Argument{ &first.arg, &second.arg, &third.arg, &fourth.arg };
var posArgs = [_]*arguments.PositionalArgument{ &name.arg, &age.arg, &optional.arg };
arguments.parse(allocator, &args, &posArgs) catch return;
if (first.found) {
std.debug.print("First: {}\n", .{first.value});
} else {
std.debug.print("First:\n", .{});
}
std.debug.print("Second: {s}\n", .{if (second.found) second.value else "N/A"});
std.debug.print("Third: {}\n", .{third.found});
std.debug.print("Fourth: {}\n\n", .{fourth.found});
std.debug.print("Name: {s}\n", .{name.value});
std.debug.print("Age: {}\n", .{age.value});
std.debug.print("Optional: {s}\n", .{optional.value});
}

387
src/root.zig Normal file
View File

@ -0,0 +1,387 @@
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const ParseError = error{
UnknownArgument,
MissingArgumentValue,
MissingPositionalArgument,
BadPositionalArguments,
InvalidInteger,
};
const Parser = struct {
current: []const u8 = undefined,
isLongArg: bool = false,
isShortArg: bool = false,
vtable: struct {
next: *const fn (self: *Parser) bool,
},
fn next(self: *Parser) bool {
return self.vtable.next(self);
}
fn parse(self: *Parser, args: []*Argument, posArgs: []*PositionalArgument) !void {
if (args.len == 0 and posArgs.len == 0) {
return;
}
if (posArgs.len > 1) {
var i: usize = 0;
while (i < posArgs.len - 1) {
if (!posArgs[i].required and posArgs[i + 1].required) {
std.debug.print("All required positional arguments must come before optional positional arguments\n", .{});
return ParseError.BadPositionalArguments;
}
i += 1;
}
}
var posIndex: usize = 0;
while (self.next()) {
if (self.isLongArg) {
const arg = self.current;
self.findMatch(args, arg[2..]) catch |err| {
switch (err) {
ParseError.UnknownArgument => std.debug.print("Unknown argument {s}\n", .{arg}),
ParseError.MissingArgumentValue => std.debug.print("Missing argument value for {s}\n", .{arg}),
ParseError.InvalidInteger => std.debug.print("{s} expects an integer value, got {s} instead\n", .{ arg, self.current }),
else => std.debug.print("Unexpected error occurred\n", .{}),
}
return err;
};
} else if (self.isShortArg) {
// Short argument
for (1..self.current.len) |i| {
const arg = self.current[i];
self.findShortMatches(args, arg, i == self.current.len - 1) catch |err| {
switch (err) {
ParseError.UnknownArgument => std.debug.print("Unknown argument -{c}\n", .{arg}),
ParseError.MissingArgumentValue => std.debug.print("Missing argument value for -{c}\n", .{arg}),
ParseError.InvalidInteger => std.debug.print("-{c} expects an integer value, got {s} instead\n", .{ arg, self.current }),
else => std.debug.print("Unexpected error occurred\n", .{}),
}
return err;
};
}
} else {
// Positional Argument
if (posIndex >= posArgs.len) {
std.debug.print("Unknown argument {s}\n", .{self.current});
return ParseError.UnknownArgument;
}
posArgs[posIndex].parse(self.current) catch |err| {
switch (err) {
ParseError.InvalidInteger => std.debug.print("Expected integer positional argument, got {s} instead\n", .{self.current}),
else => std.debug.print("Unexpected error occurred\n", .{}),
}
return err;
};
posIndex += 1;
}
}
if (posIndex < posArgs.len and posArgs[posIndex].required) {
std.debug.print("Missing required positional argument\n", .{});
return ParseError.MissingPositionalArgument;
}
}
fn findMatch(self: *Parser, args: []*Argument, str: []const u8) !void {
for (args) |arg| {
if (arg.matches(str)) {
try arg.parse(self);
return;
}
}
return ParseError.UnknownArgument;
}
fn findShortMatches(self: *Parser, args: []*Argument, c: u8, last: bool) !void {
for (args) |arg| {
if (arg.shortMatches(c)) {
if (last) {
try arg.parse(self);
} else {
try arg.noVal();
try arg.parse(self);
}
return;
}
}
return ParseError.UnknownArgument;
}
};
const ArgvParser = struct {
index: usize,
parser: Parser,
fn init() ArgvParser {
return .{
.index = 0,
.parser = .{ .vtable = .{
.next = ArgvParser.next,
} },
};
}
fn next(parser: *Parser) bool {
var self: *ArgvParser = @fieldParentPtr("parser", parser);
if (self.index + 1 >= std.os.argv.len) {
return false;
}
self.index += 1;
self.parser.current = std.mem.span(std.os.argv[self.index]);
self.parser.isLongArg = false;
self.parser.isShortArg = false;
if (self.parser.current.len >= 2 and self.parser.current[0] == '-') {
self.parser.isShortArg = self.parser.current[1] != '-';
if (self.parser.current.len >= 3) {
self.parser.isLongArg = self.parser.current[1] == '-';
}
}
return true;
}
};
const AllocParser = struct {
parser: Parser,
current: []const u8,
args: std.process.ArgIterator,
fn init(allocator: std.mem.Allocator) !AllocParser {
var self = AllocParser{
.args = try std.process.argsWithAllocator(allocator),
.current = undefined,
.parser = .{ .vtable = .{
.next = AllocParser.next,
} },
};
_ = self.args.next();
return self;
}
fn deinit(self: *AllocParser) void {
self.args.deinit();
}
fn next(parser: *Parser) bool {
var self: *AllocParser = @fieldParentPtr("parser", parser);
const val = self.args.next();
if (val == null) {
return false;
}
self.parser.current = val.?;
self.parser.isLongArg = false;
self.parser.isShortArg = false;
if (self.parser.current.len >= 2 and self.parser.current[0] == '-') {
self.parser.isShortArg = self.parser.current[1] != '-';
if (self.parser.current.len >= 3) {
self.parser.isLongArg = self.parser.current[1] == '-';
}
}
return true;
}
};
pub const Argument = struct {
names: []const []const u8,
shortNames: []const u8,
vtable: struct {
parse: *const fn (arg: *Argument, parser: *Parser) ParseError!void,
noVal: *const fn () ParseError!void,
},
fn matches(self: *Argument, arg: []const u8) bool {
for (self.names) |alias| {
if (std.mem.eql(u8, arg, alias)) {
return true;
}
}
return false;
}
fn shortMatches(self: *Argument, arg: u8) bool {
for (self.shortNames) |alias| {
if (arg == alias) {
return true;
}
}
return false;
}
fn parse(self: *Argument, parser: *Parser) ParseError!void {
try self.vtable.parse(self, parser);
}
fn noVal(self: *Argument) ParseError!void {
return self.vtable.noVal();
}
};
pub const IntArgument = struct {
arg: Argument,
value: isize,
found: bool,
pub fn init(names: []const []const u8, shortNames: []const u8, defaultValue: isize) IntArgument {
return .{
.found = false,
.value = defaultValue,
.arg = .{ .names = names, .shortNames = shortNames, .vtable = .{ .noVal = IntArgument.noVal, .parse = IntArgument.parse } },
};
}
fn parse(arg: *Argument, parser: *Parser) ParseError!void {
var self: *IntArgument = @fieldParentPtr("arg", arg);
if (parser.next() and !parser.isLongArg) {
self.found = true;
self.value = std.fmt.parseInt(isize, parser.current, 0) catch {
return ParseError.InvalidInteger;
};
} else {
return ParseError.MissingArgumentValue;
}
}
fn noVal() ParseError!void {
return ParseError.MissingArgumentValue;
}
};
pub const StringArgument = struct {
arg: Argument,
value: []const u8,
found: bool,
pub fn init(names: []const []const u8, shortNames: []const u8, defaultVal: []const u8) StringArgument {
return .{
.found = false,
.value = defaultVal,
.arg = .{ .names = names, .shortNames = shortNames, .vtable = .{ .noVal = StringArgument.noVal, .parse = StringArgument.parse } },
};
}
fn parse(arg: *Argument, parser: *Parser) ParseError!void {
var self: *StringArgument = @fieldParentPtr("arg", arg);
if (parser.next() and !parser.isLongArg and !parser.isShortArg) {
self.found = true;
self.value = parser.current;
} else {
return ParseError.MissingArgumentValue;
}
}
fn noVal() ParseError!void {
return ParseError.MissingArgumentValue;
}
};
pub const BoolArgument = struct {
arg: Argument,
found: bool,
pub fn init(names: []const []const u8, shortNames: []const u8) BoolArgument {
return .{
.found = false,
.arg = .{ .names = names, .shortNames = shortNames, .vtable = .{ .noVal = BoolArgument.noVal, .parse = BoolArgument.parse } },
};
}
fn parse(arg: *Argument, parser: *Parser) ParseError!void {
_ = parser;
var self: *BoolArgument = @fieldParentPtr("arg", arg);
self.found = true;
}
fn noVal() ParseError!void {
return;
}
};
pub const PositionalArgument = struct {
required: bool,
vtable: struct {
parse: *const fn (arg: *PositionalArgument, value: []const u8) ParseError!void,
},
fn parse(self: *PositionalArgument, value: []const u8) ParseError!void {
try self.vtable.parse(self, value);
}
};
pub const PositionalIntArgument = struct {
arg: PositionalArgument,
value: isize,
found: bool,
pub fn init(defaultValue: isize, required: bool) PositionalIntArgument {
return .{
.found = false,
.value = defaultValue,
.arg = .{ .required = required, .vtable = .{ .parse = PositionalIntArgument.parse } },
};
}
fn parse(arg: *PositionalArgument, value: []const u8) ParseError!void {
var self: *PositionalIntArgument = @fieldParentPtr("arg", arg);
self.found = true;
self.value = std.fmt.parseInt(isize, value, 0) catch {
return ParseError.InvalidInteger;
};
}
};
pub const PositionalStringArgument = struct {
arg: PositionalArgument,
value: []const u8,
found: bool,
pub fn init(defaultValue: []const u8, required: bool) PositionalStringArgument {
return .{
.found = false,
.value = defaultValue,
.arg = .{ .required = required, .vtable = .{ .parse = PositionalStringArgument.parse } },
};
}
fn parse(arg: *PositionalArgument, value: []const u8) ParseError!void {
var self: *PositionalStringArgument = @fieldParentPtr("arg", arg);
self.found = true;
self.value = value;
}
};
pub fn parse(allocator: std.mem.Allocator, args: []*Argument, posArgs: []*PositionalArgument) !void {
var allocParser: AllocParser = try AllocParser.init(allocator);
defer allocParser.deinit();
try allocParser.parser.parse(args, posArgs);
}
pub fn parseArgv(args: []*Argument, posArgs: []*PositionalArgument) !void {
var argvParser: ArgvParser = ArgvParser.init();
try argvParser.parser.parse(args, posArgs);
}
test "basic add functionality" {}