Something went wrong. Try again.
Zig bindings for all 506 operations of the Forgejo API, generated from its own description, and zfj, a command line built on them.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The command line, read into a struct: one `--name` flag per field, spelled//! exactly as the field is.//!//! A plumbing command's flags are its operation's params, so the struct is//! the params struct the bindings generate and nothing here knows which//! operation it is. The global options are read the same way, out of the//! words ahead of the command (docs/adr/0003-global-options-before-the-command.md).//!//! - `--name value` and `--name=value` are the same thing.//! - A boolean is `--name` for true, or `--name=true` / `--name=false`; it//! never takes the next word, so `--draft main` is not a boolean and a word.//! - A field that is not optional and has no default is required.//! - A slice field (other than a string) takes the flag once per element.//! - Anything else given twice is a mistake rather than the last one winning.//! - A file to upload -- a struct with a `filename` and `bytes`, as the//! bindings' `FormFile` is -- is given as a path, which is kept in//! `filename` with `bytes` left empty for the caller to load.//! - A struct may declare `pub const short = .{ .t = "title" }`, giving//! fields one-letter spellings (`-t`), and `pub const positional =//! &.{"number"}`, the fields that bare words fill, in order. Porcelain//! commands use both; a params struct declares neither, so every word of//! a plumbing command is a `--name` flag.//! - A struct may also declare `pub const rest = "field"`, a slice of//! strings that takes every word after a `--`, flag or not: what a//! command hands on to another program.
const std = @import("std");const Allocator = std.mem.Allocator;
pub const Error = error{Usage} || Allocator.Error;
/// What went wrong, in words, when parsing fails with `error.Usage`.pub const Diagnostic = struct { buffer: [256]u8 = undefined, len: usize = 0,
pub fn set(self: *Diagnostic, comptime format: []const u8, args: anytype) error{Usage} { const written = std.fmt.bufPrint(&self.buffer, format, args) catch blk: { const ellipsis = "..."; @memcpy(self.buffer[self.buffer.len - ellipsis.len ..], ellipsis); break :blk self.buffer[0..]; }; self.len = written.len; return error.Usage; }
pub fn message(self: *const Diagnostic) []const u8 { return self.buffer[0..self.len]; }};
pub const Mode = enum { /// Every word must be a flag: a plumbing command's arguments. all, /// Stop at the first word that is not a flag, and report where: the /// global options, which end at the command. leading,};
pub fn Parsed(comptime T: type) type { return struct { value: T, /// The index of the first word not consumed. Always the number of /// words given, in `.all` mode. rest: usize, };}
/// Reads `words` into a `T`. Every string in the result points into `words`;/// slices built for repeated flags are allocated from `arena`.pub fn parse( comptime T: type, arena: Allocator, words: []const []const u8, mode: Mode, diagnostic: *Diagnostic,) Error!Parsed(T) { const info = @typeInfo(T).@"struct"; const n = info.field_names.len;
var result: T = undefined; var seen: [n]bool = @splat(false); // Repeated flags for slice fields, gathered in order and turned into // slices once every word has been read. var elements: [n]std.ArrayList([]const u8) = @splat(.empty);
const positionals: []const []const u8 = if (@hasDecl(T, "positional")) T.positional else &.{}; var next_positional: usize = 0;
var index: usize = 0; while (index < words.len) : (index += 1) { const word = words[index]; if (comptime @hasDecl(T, "rest")) { if (mode == .all and std.mem.eql(u8, word, "--")) { @field(result, T.rest) = words[index + 1 ..]; seen[comptime fieldIndex(T, T.rest).?] = true; index = words.len; break; } } var field_index: usize = undefined; var inline_value: ?[]const u8 = null; var name: []const u8 = undefined; if (std.mem.startsWith(u8, word, "--") and word.len > 2) { const flag = word[2..]; const equals = std.mem.findScalar(u8, flag, '='); name = if (equals) |e| flag[0..e] else flag; inline_value = if (equals) |e| flag[e + 1 ..] else null; field_index = fieldIndex(T, name) orelse return diagnostic.set("unknown option '--{s}'", .{name}); } else if (word.len == 2 and word[0] == '-' and word[1] != '-') { name = shortField(T, word[1]) orelse return diagnostic.set("unknown option '{s}'", .{word}); field_index = fieldIndex(T, name).?; } else { if (mode == .leading) break; if (comptime positionals.len == 0) return diagnostic.set("unexpected argument '{s}'", .{word}); if (next_positional == positionals.len) return diagnostic.set("unexpected argument '{s}'", .{word}); name = positionals[next_positional]; next_positional += 1; field_index = fieldIndex(T, name).?; inline_value = word; }
inline for (0..n) |i| { if (i == field_index) { const Field = info.field_types[i]; const Value = Unwrapped(Field); const value: []const u8 = if (Value == bool) inline_value orelse "true" else if (inline_value) |v| v else blk: { index += 1; if (index == words.len) return diagnostic.set("--{s} needs a value", .{name}); break :blk words[index]; };
if (comptime isList(Value)) { try elements[i].append(arena, value); } else { if (seen[i]) return diagnostic.set("--{s} given more than once", .{name}); @field(result, info.field_names[i]) = try scalar(Value, name, value, diagnostic); } seen[i] = true; } } }
inline for (0..n) |i| { const Field = info.field_types[i]; const Value = Unwrapped(Field); const field_name = info.field_names[i]; if (comptime isList(Value) and !isRest(T, field_name)) { if (seen[i]) { const Element = @typeInfo(Value).pointer.child; const list = try arena.alloc(Element, elements[i].items.len); for (elements[i].items, list) |text, *element| { element.* = try scalar(Element, field_name, text, diagnostic); } @field(result, field_name) = list; } } if (!seen[i]) { if (info.field_attrs[i].defaultValue(Field)) |default| { @field(result, field_name) = default; } else if (@typeInfo(Field) == .optional) { @field(result, field_name) = null; } else if (comptime isPositional(T, field_name)) { return diagnostic.set("<{s}> is required", .{field_name}); } else { return diagnostic.set("--{s} is required", .{field_name}); } } }
return .{ .value = result, .rest = index };}
fn fieldIndex(comptime T: type, name: []const u8) ?usize { inline for (@typeInfo(T).@"struct".field_names, 0..) |field_name, i| { if (std.mem.eql(u8, field_name, name)) return i; } return null;}
/// The field a one-letter flag stands for, from the struct's `short`.fn shortField(comptime T: type, letter: u8) ?[]const u8 { if (!@hasDecl(T, "short")) return null; const Short = @TypeOf(T.short); inline for (@typeInfo(Short).@"struct".field_names) |key| { if (key.len == 1 and key[0] == letter) return @field(T.short, key); } return null;}
/// The one-letter spelling of a field, if it has one.fn shortOf(comptime T: type, comptime field_name: []const u8) ?u8 { if (!@hasDecl(T, "short")) return null; const Short = @TypeOf(T.short); inline for (@typeInfo(Short).@"struct".field_names) |key| { if (comptime std.mem.eql(u8, @field(T.short, key), field_name)) return key[0]; } return null;}
fn isPositional(comptime T: type, comptime field_name: []const u8) bool { if (!@hasDecl(T, "positional")) return false; inline for (T.positional) |p| { if (comptime std.mem.eql(u8, p, field_name)) return true; } return false;}
fn isRest(comptime T: type, comptime field_name: []const u8) bool { return @hasDecl(T, "rest") and std.mem.eql(u8, T.rest, field_name);}
fn Unwrapped(comptime Field: type) type { return switch (@typeInfo(Field)) { .optional => |o| o.child, else => Field, };}
/// A slice of anything but bytes: a flag that may be given more than once.fn isList(comptime Value: type) bool { return switch (@typeInfo(Value)) { .pointer => |p| p.size == .slice and p.child != u8, else => false, };}
fn scalar(comptime Value: type, name: []const u8, text: []const u8, diagnostic: *Diagnostic) error{Usage}!Value { if (Value == []const u8) return text; if (Value == bool) { if (std.mem.eql(u8, text, "true")) return true; if (std.mem.eql(u8, text, "false")) return false; return diagnostic.set("--{s} is true or false, not '{s}'", .{ name, text }); } if (comptime isFile(Value)) return .{ .filename = text, .bytes = "" }; switch (@typeInfo(Value)) { .int => return std.fmt.parseInt(Value, text, 10) catch diagnostic.set("--{s} is an integer, not '{s}'", .{ name, text }), .float => return std.fmt.parseFloat(Value, text) catch diagnostic.set("--{s} is a number, not '{s}'", .{ name, text }), .@"enum" => return std.meta.stringToEnum(Value, text) orelse diagnostic.set("--{s} is one of {s}, not '{s}'", .{ name, comptime choices(Value), text }), else => @compileError("no flag can be read into a " ++ @typeName(Value)), }}
/// A file to upload, read from a path: a struct with a `filename` and `bytes`.pub fn isFile(comptime Value: type) bool { return @typeInfo(Value) == .@"struct" and @hasField(Value, "filename") and @hasField(Value, "bytes");}
fn choices(comptime E: type) []const u8 { comptime { var text: []const u8 = ""; for (@typeInfo(E).@"enum".field_names, 0..) |field_name, i| { text = text ++ (if (i == 0) "" else ", ") ++ field_name; } return text; }}
/// What the help says about a field beyond its type.pub const Note = struct { description: ?[]const u8 = null, /// The only values the field takes, shown in place of its type. allowed: []const []const u8 = &.{}, /// What a shell completes the field's value from, beyond `allowed`. complete: Complete = .none,};
/// Where the candidates for a value come from when it is not one of a/// fixed set.pub const Complete = enum { /// Nowhere: a number, a name, anything zfj cannot know. none, /// The file system: a file to read or upload. files, /// The file system's directories. dirs, /// The names of the configured instances. instances, /// The workflow files of the clone the command is run in. workflows,};
/// A command line's options and positional words, for completing it: read/// from the same struct, `short`, `positional`, `rest` and notes as `parse`/// and `writeHelp` are, so that completion offers exactly what parses.pub const Spec = struct { options: []const Field = &.{}, positionals: []const Field = &.{}, /// Whether the words after a `--` are handed on to another program. rest: bool = false,
pub const Field = struct { name: []const u8, short: ?u8 = null, /// A flag that takes the next word as its value; a boolean does not. takes_value: bool = true, /// The only values it takes: the note's `allowed`, or an enum's tags. values: []const []const u8 = &.{}, /// The first line of what the note says of it. description: []const u8 = "", complete: Complete = .none, };
pub fn option(self: Spec, name: []const u8) ?Field { for (self.options) |field| if (std.mem.eql(u8, field.name, name)) return field; return null; }
pub fn shortOption(self: Spec, letter: u8) ?Field { for (self.options) |field| if (field.short == letter) return field; return null; }};
/// The `Spec` of a struct `parse` reads, with `notes` in field order as for/// `writeHelp`.pub fn spec(comptime T: type, comptime notes: []const Note) Spec { comptime { @setEvalBranchQuota(100_000); const info = @typeInfo(T).@"struct"; var options: []const Spec.Field = &.{}; var positionals: []const Spec.Field = &.{}; for (info.field_names, info.field_types, 0..) |field_name, Field, i| { if (isRest(T, field_name)) continue; const Value = Unwrapped(Field); const Element = if (isList(Value)) @typeInfo(Value).pointer.child else Value; const note: Note = if (i < notes.len) notes[i] else .{}; const field: Spec.Field = .{ .name = field_name, .short = shortOf(T, field_name), .takes_value = Value != bool, .values = if (note.allowed.len != 0) note.allowed else if (@typeInfo(Element) == .@"enum") @typeInfo(Element).@"enum".field_names else &.{}, .description = firstLine(note.description orelse ""), .complete = if (isFile(Element)) .files else note.complete, }; if (isPositional(T, field_name)) { positionals = positionals ++ .{field}; } else { options = options ++ .{field}; } } // In the order bare words fill them, which need not be field order. var ordered: []const Spec.Field = &.{}; if (@hasDecl(T, "positional")) for (T.positional) |name| { for (positionals) |field| if (std.mem.eql(u8, field.name, name)) { ordered = ordered ++ .{field}; }; }; const frozen_options = options[0..options.len].*; const frozen_positionals = ordered[0..ordered.len].*; return .{ .options = &frozen_options, .positionals = &frozen_positionals, .rest = @hasDecl(T, "rest") }; }}
fn firstLine(text: []const u8) []const u8 { const trimmed = std.mem.trim(u8, text, " \r\n"); return trimmed[0 .. std.mem.findAny(u8, trimmed, "\r\n") orelse trimmed.len];}
/// One entry per field: the flag, what it takes, whether it is required,/// and beneath it what `notes` says of it. `notes` is in field order, and may/// be shorter than the fields or empty.pub fn writeHelp(comptime T: type, writer: *std.Io.Writer, notes: []const Note) std.Io.Writer.Error!void { const info = @typeInfo(T).@"struct"; if (info.field_names.len == 0) return writer.writeAll(" (none)\n"); inline for (info.field_names, info.field_types, info.field_attrs, 0..) |field_name, Field, attrs, i| { const Value = Unwrapped(Field); const note: Note = if (i < notes.len) notes[i] else .{}; const required = @typeInfo(Field) != .optional and attrs.defaultValue(Field) == null; if (comptime isPositional(T, field_name)) { try writer.print(" <{s}>", .{field_name}); } else if (comptime isRest(T, field_name)) { try writer.print(" -- <{s}>...", .{field_name}); } else { if (comptime shortOf(T, field_name)) |letter| { try writer.print(" -{c}, --{s}", .{ letter, field_name }); } else { try writer.print(" --{s}", .{field_name}); } if (Value != bool or note.allowed.len != 0) { try writer.writeAll(" <"); if (note.allowed.len != 0) { for (note.allowed, 0..) |value, j| try writer.print("{s}{s}", .{ if (j == 0) "" else "|", value }); } else { try writer.writeAll(comptime describe(Value)); } try writer.writeByte('>'); } if (comptime isList(Value)) try writer.writeAll(", repeatable"); } try writer.print("{s}\n", .{if (required) " (required)" else ""}); if (note.description) |description| { var lines = std.mem.splitScalar(u8, std.mem.trim(u8, description, " \r\n"), '\n'); while (lines.next()) |line| try writer.print(" {s}\n", .{std.mem.trimEnd(u8, line, " \r")}); } }}
fn describe(comptime Value: type) []const u8 { if (Value == []const u8) return "string"; if (Value == bool) return "true|false"; if (comptime isFile(Value)) return "path"; if (comptime isList(Value)) return describe(@typeInfo(Value).pointer.child); return switch (@typeInfo(Value)) { .int => "integer", .float => "number", .@"enum" => choices(Value), else => @typeName(Value), };}
const testing = std.testing;
const Example = struct { owner: []const u8, index: i64, state: ?[]const u8 = null, page: ?i64 = null, draft: ?bool = null, color: ?[]const u8 = null, labels: ?[]const i64 = null, names: ?[]const []const u8 = null,};
fn parseAll(arena: Allocator, words: []const []const u8, diagnostic: *Diagnostic) Error!Example { return (try parse(Example, arena, words, .all, diagnostic)).value;}
test "a flag takes the next word or what follows its equals sign" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; const e = try parseAll(arena.allocator(), &.{ "--owner", "jeff", "--index=42", "--state=open" }, &d); try testing.expectEqualStrings("jeff", e.owner); try testing.expectEqual(@as(i64, 42), e.index); try testing.expectEqualStrings("open", e.state.?); try testing.expect(e.page == null);}
test "a required flag left out is a usage error naming it" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; try testing.expectError(error.Usage, parseAll(arena.allocator(), &.{ "--owner", "jeff" }, &d)); try testing.expectEqualStrings("--index is required", d.message());}
test "an integer flag rejects what is not one" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; try testing.expectError(error.Usage, parseAll(arena.allocator(), &.{ "--owner", "jeff", "--index", "four" }, &d)); try testing.expectEqualStrings("--index is an integer, not 'four'", d.message());}
test "a boolean is true alone, and takes a value only after an equals sign" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; const on = try parseAll(arena.allocator(), &.{ "--draft", "--owner", "jeff", "--index", "1" }, &d); try testing.expectEqual(true, on.draft.?); const off = try parseAll(arena.allocator(), &.{ "--draft=false", "--owner", "jeff", "--index", "1" }, &d); try testing.expectEqual(false, off.draft.?); try testing.expectError(error.Usage, parseAll(arena.allocator(), &.{ "--draft=maybe", "--owner", "jeff", "--index", "1" }, &d));}
test "a list flag is given once per element" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; const e = try parseAll(arena.allocator(), &.{ "--owner", "jeff", "--index", "1", "--labels", "7", "--labels=9", "--names", "a" }, &d); try testing.expectEqualSlices(i64, &.{ 7, 9 }, e.labels.?); try testing.expectEqual(@as(usize, 1), e.names.?.len); try testing.expectEqualStrings("a", e.names.?[0]); try testing.expectError(error.Usage, parseAll(arena.allocator(), &.{ "--owner", "jeff", "--index", "1", "--labels", "bug" }, &d)); try testing.expectEqualStrings("--labels is an integer, not 'bug'", d.message());}
test "anything else given twice is a usage error" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; try testing.expectError(error.Usage, parseAll(arena.allocator(), &.{ "--owner", "a", "--owner", "b", "--index", "1" }, &d)); try testing.expectEqualStrings("--owner given more than once", d.message());}
test "an unknown flag or a bare word is a usage error" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; try testing.expectError(error.Usage, parseAll(arena.allocator(), &.{"--nope"}, &d)); try testing.expectEqualStrings("unknown option '--nope'", d.message()); try testing.expectError(error.Usage, parseAll(arena.allocator(), &.{"jeff"}, &d)); try testing.expectEqualStrings("unexpected argument 'jeff'", d.message());}
test "a param named like a global option is just a param" { // The reason global options are only read before the command: `color` // and `page` are params of real operations, and here they are only that. var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; const e = try parseAll(arena.allocator(), &.{ "--owner", "jeff", "--index", "1", "--color", "ff0000", "--page", "2" }, &d); try testing.expectEqualStrings("ff0000", e.color.?); try testing.expectEqual(@as(i64, 2), e.page.?);}
test "leading mode stops at the command and says where it is" { const Global = struct { instance: ?[]const u8 = null, debug: bool = false, color: enum { auto, always, never } = .auto, }; var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; const words: []const []const u8 = &.{ "--debug", "--color=never", "op", "getVersion", "--instance", "x" }; const parsed = try parse(Global, arena.allocator(), words, .leading, &d); try testing.expect(parsed.value.debug); try testing.expectEqual(.never, parsed.value.color); try testing.expect(parsed.value.instance == null); try testing.expectEqual(@as(usize, 2), parsed.rest);
try testing.expectError(error.Usage, parse(Global, arena.allocator(), &.{"--color=red"}, .leading, &d)); try testing.expectEqualStrings("--color is one of auto, always, never, not 'red'", d.message());}
test "help lists every flag with what it takes" { var buffer: [512]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try writeHelp(Example, &writer, &.{}); try testing.expectEqualStrings( \\ --owner <string> (required) \\ --index <integer> (required) \\ --state <string> \\ --page <integer> \\ --draft \\ --color <string> \\ --labels <integer>, repeatable \\ --names <string>, repeatable \\ , writer.buffered());}
test "help says what the notes say, and shows allowed values for the type" { var buffer: [512]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try writeHelp(Example, &writer, &.{ .{ .description = "owner of the repo" }, .{}, .{ .description = "whether issue is open\nor closed", .allowed = &.{ "open", "closed" } }, }); try testing.expect(std.mem.startsWith(u8, writer.buffered(), \\ --owner <string> (required) \\ owner of the repo \\ --index <integer> (required) \\ --state <open|closed> \\ whether issue is open \\ or closed \\ --page <integer> \\ ));}
test "a spec says what parses: options, their values, and positional words in order" { const Thing = struct { second: ?[]const u8 = null, first: []const u8, state: []const u8 = "open", color: enum { red, blue } = .red, quiet: bool = false, @"pass-on": []const []const u8 = &.{},
pub const short = .{ .s = "state", .q = "quiet" }; pub const positional: []const []const u8 = &.{ "first", "second" }; pub const rest = "pass-on"; }; const s = comptime spec(Thing, &.{ .{ .description = "the second\nand more", .complete = .dirs }, .{}, .{ .description = "which", .allowed = &.{ "open", "closed" } }, }); try testing.expectEqual(@as(usize, 2), s.positionals.len); try testing.expectEqualStrings("first", s.positionals[0].name); try testing.expectEqualStrings("second", s.positionals[1].name); try testing.expectEqualStrings("the second", s.positionals[1].description); try testing.expectEqual(.dirs, s.positionals[1].complete); try testing.expectEqual(@as(usize, 3), s.options.len); try testing.expectEqual(@as(u8, 's'), s.option("state").?.short.?); try testing.expectEqualStrings("closed", s.option("state").?.values[1]); try testing.expectEqualStrings("blue", s.option("color").?.values[1]); try testing.expect(!s.shortOption('q').?.takes_value); try testing.expect(s.rest);}
test "the words after -- are handed on whole, flags and all" { const Passing = struct { name: []const u8, verbose: bool = false, @"git-args": []const []const u8 = &.{},
pub const positional: []const []const u8 = &.{"name"}; pub const rest = "git-args"; }; var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; const passed = (try parse(Passing, arena.allocator(), &.{ "thing", "--", "--depth", "1", "--verbose" }, .all, &d)).value; try testing.expectEqualStrings("thing", passed.name); try testing.expect(!passed.verbose); try testing.expectEqual(@as(usize, 3), passed.@"git-args".len); try testing.expectEqualStrings("--verbose", passed.@"git-args"[2]); const none = (try parse(Passing, arena.allocator(), &.{"thing"}, .all, &d)).value; try testing.expectEqual(@as(usize, 0), none.@"git-args".len); // Without a `rest`, a -- is a word like any other. try testing.expectError(error.Usage, parse(Example, arena.allocator(), &.{ "--owner", "jeff", "--index", "1", "--" }, .all, &d));}
test "short flags and positional words fill the fields that declare them" { const View = struct { number: i64, repo: ?[]const u8 = null, comments: bool = false, label: ?[]const []const u8 = null,
pub const short = .{ .R = "repo", .l = "label" }; pub const positional: []const []const u8 = &.{"number"}; }; var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; const v = (try parse(View, arena.allocator(), &.{ "-R", "jeff/zfj", "42", "--comments", "-l", "bug", "-l", "-" }, .all, &d)).value; try testing.expectEqual(@as(i64, 42), v.number); try testing.expectEqualStrings("jeff/zfj", v.repo.?); try testing.expect(v.comments); // A flag takes the next word whatever it is, so `-` reaches it as a value. try testing.expectEqualStrings("-", v.label.?[1]);
try testing.expectError(error.Usage, parse(View, arena.allocator(), &.{"-R"}, .all, &d)); try testing.expectEqualStrings("--repo needs a value", d.message()); try testing.expectError(error.Usage, parse(View, arena.allocator(), &.{"--comments"}, .all, &d)); try testing.expectEqualStrings("<number> is required", d.message()); try testing.expectError(error.Usage, parse(View, arena.allocator(), &.{ "1", "2" }, .all, &d)); try testing.expectEqualStrings("unexpected argument '2'", d.message()); try testing.expectError(error.Usage, parse(View, arena.allocator(), &.{ "1", "-x" }, .all, &d)); try testing.expectEqualStrings("unknown option '-x'", d.message());
var buffer: [512]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try writeHelp(View, &writer, &.{}); try testing.expectEqualStrings( \\ <number> (required) \\ -R, --repo <string> \\ --comments \\ -l, --label <string>, repeatable \\ , writer.buffered());}
test "a file to upload is given as a path" { const Upload = struct { attachment: struct { filename: []const u8, content_type: ?[]const u8 = null, bytes: []const u8 }, name: ?[]const u8 = null, }; var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var d: Diagnostic = .{}; const u = (try parse(Upload, arena.allocator(), &.{ "--attachment", "notes/report.pdf" }, .all, &d)).value; try testing.expectEqualStrings("notes/report.pdf", u.attachment.filename); try testing.expectEqual(@as(usize, 0), u.attachment.bytes.len);
var buffer: [128]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); try writeHelp(Upload, &writer, &.{}); try testing.expect(std.mem.startsWith(u8, writer.buffered(), " --attachment <path> (required)\n"));}