Something went wrong. Try again.
Charm-like tui library
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308const std = @import("std");const builtin = @import("builtin");const Arg = @import("Arg.zig");const help = @import("help.zig");const Config = @import("Config.zig");
const t = std.testing;const Allocator = std.mem.Allocator;const Alignment = std.mem.Alignment;
const StringArrayHashMap = std.StringArrayHashMapUnmanaged;
pub fn funcName(func: anytype) []const u8 { const func_name = @typeName(Dummy(func)); const start = (std.mem.findScalar(u8, func_name, '\'') orelse unreachable) + 1; const end = std.mem.findScalarPos(u8, func_name, start, '\'') orelse unreachable; return func_name[start..end];}
pub fn fullFuncName(func: anytype) []const u8 { return @typeName(Dummy(func));}
fn Dummy(func: anytype) type { return struct { fn warpper() void { func(); } };}
pub fn typeName(comptime T: type) []const u8 { const full = @typeName(T); return if (std.mem.findScalarLast(u8, full, '.')) |i| full[i + 1 ..] else full;}
pub fn typeText(comptime T: type) []const u8 { const type_info: std.lang.Type = @typeInfo(T); return switch (type_info) { .array => |array| typeText(array.child) ++ " list", .bool => flag, .optional => |optional| typeText(optional.child), .@"enum" => "choice", .float => "decimal", .int => "integer", .pointer => |pointer| blk: { if (pointer.size != .slice) @compileError("Not yet written"); if (pointer.child == u8) break :blk "text"; break :blk typeText(pointer.child) ++ " list"; }, else => @compileError("Not yet written"), };}
test typeText { try t.expectEqualStrings("integer", comptime typeText(i128)); try t.expectEqualStrings("text", comptime typeText([]const u8)); try t.expectEqualStrings("integer list", comptime typeText([4]i128)); try t.expectEqualStrings("integer list", comptime typeText([]i128)); try t.expectEqualStrings("integer list", comptime typeText([]const i128)); try t.expectEqualStrings("text list", comptime typeText([][]const u8));}
pub const flag: []const u8 = switch (builtin.os.tag) { .windows => "switch", else => "flag",};
pub fn printGroupHelp( io: std.Io, description: ?[]const u8, chain: []const []const u8, group: ?Arg, cmd_list: []const Arg, comptime config: Config,) !void { var buf: [4096]u8 = undefined; var w = std.Io.File.stderr().writer(io, &buf); try help.printGroup(&w.interface, description, chain, group, cmd_list, config); try w.interface.flush();}
pub fn isHelpFlag(s: []const u8) bool { return std.mem.eql(u8, s, "--help") or std.mem.eql(u8, s, "-h") or std.mem.eql(u8, s, "--?") or std.mem.eql(u8, s, "-?");}
pub fn freeArgMap(allocator: std.mem.Allocator, map: *StringArrayHashMap([]const u8)) void { map.deinit(allocator);}
pub const Info = struct { name: []const u8, description: []const u8, type_text: []const u8, optional: Optional(?[]const u8), enum_values: ?[]const []const u8 = null, min_length: ?usize = null, max_length: ?usize = null, min_value: ?f128 = null, max_value: ?f128 = null, /// Index of the last character of `name` required to uniquely identify /// it among its sibling params. Computed at comptime when the sibling /// list is assembled. When `name` is a prefix of a sibling this is /// `name.len - 1`, covered only by an exact match (matchers resolve /// exact matches first). unique_index: ?usize = null,};
/// Returns a comptime copy of `items` with each `unique_index` set.pub fn withUniqueIndices( comptime T: type, comptime items: []const T, comptime field_name: []const u8,) [items.len]T { const indices = comptime uniqueIndices(T, items, field_name); var copy: [items.len]T = items[0..items.len].*; for (©, indices) |*item, index| item.unique_index = index; return copy;}
/// Returns, for each item, the index of the last character of/// `field_name` required to uniquely identify it among its siblings./// When an item is a proper prefix of a sibling it cannot be identified/// by prefix alone; its index is its last character, so only an exact/// match covers the index (matchers resolve exact matches first).////// Compile-errors on duplicate names, which no input can disambiguate.pub fn uniqueIndices( comptime T: type, comptime items: []const T, comptime field_name: []const u8,) [items.len]usize { var result: [items.len]usize = undefined; for (items, 0..) |a, i| { const name_a = @field(a, field_name); var best: usize = 0; for (items, 0..) |b, j| { if (i == j) continue; const name_b = @field(b, field_name); const n = @min(name_a.len, name_b.len); var lcp: usize = 0; while (lcp < n and name_a[lcp] == name_b[lcp]) : (lcp += 1) {} if (lcp == n and name_a.len == name_b.len) @compileError("duplicate " ++ field_name ++ " '" ++ name_a ++ "'"); best = @max(best, @min(lcp, name_a.len - 1)); } result[i] = best; } return result;}
pub const StringOptions = struct { optional: Optional([]const u8) = .not, type_text: ?[]const u8 = null, min_length: ?usize = null, max_length: ?usize = null,};
pub fn NumberOptions(comptime T: type) type { return struct { optional: Optional(T) = .not, type_text: ?[]const u8 = null, min: ?T = null, max: ?T = null, };}
pub fn EnumOptions(comptime T: type) type { return struct { optional: Optional(T) = .not, type_text: ?[]const u8 = null, /// override enum name if desired name: ?[]const u8 = null, };}
pub fn Type(comptime T: type) type { return union(enum) { number_options: NumberOptions(T), string_options: StringOptions, enum_options: EnumOptions(T), };}
pub fn Optional(comptime T: type) type { return union(enum) { not, // arg is required default_value: T, // arg is optional, use this value if not supplied
pub fn default(value: T) Optional(T) { return .{ .default_value = value }; } };}
pub const Options = struct { /// Text to use for parameters type type_text: ?[]const u8 = null, /// default value to use if optional and value is null optional: Optional(?[]const u8) = .not, /// quote the default value in the description (used for strings) quote_default: bool = false, /// for arrays and strings min_length: ?usize = null, /// for arrays and strings max_length: ?usize = null, /// for numbers min_value: ?f128 = null, // to be compatible with u, i, and f /// for numbers max_value: ?f128 = null, /// auto filled for enums enum_values: ?[]const [:0]const u8 = null,};
pub inline fn writeDescription( comptime description: []const u8, comptime options: Options,) []const u8 { var result: []const u8 = description; if (options.enum_values) |values| { result = result ++ "\nOptions:"; for (values, 0..) |value, i| { if (i != 0) result = result ++ ","; result = result ++ " " ++ value; } } switch (options.optional) { .default_value => |value| { if (value) |v| { result = if (options.quote_default) result ++ "\nDefault: \"" ++ v ++ "\"" else result ++ "\nDefault: " ++ v; } else { result = result ++ "\nDefault: null"; } }, .not => {}, } return result;}
pub const Diag = struct { param: []const u8 = "", value: []const u8 = "",};
pub fn resolveParam(prefix: []const u8, params: []const Info) !Info { // Same matching rules as findMatch: exact wins, unique prefix returns // early, ambiguity is deferred to the end of the scan. var matched: ?Info = null; var ambiguous = false; for (params) |p| { if (!std.mem.startsWith(u8, p.name, prefix)) continue; if (std.mem.eql(u8, p.name, prefix)) return p; if (p.unique_index) |index| { if (prefix.len > index) return p; } if (matched != null) ambiguous = true; matched = p; } if (ambiguous) return error.Ambiguous; return matched orelse error.Unknown;}
pub fn findMatch(list: []const Arg, input: []const u8) !Arg { // Exact matches always win, and a prefix match covering the // comptime-computed unique prefix is guaranteed to be the only one, so // both return immediately. Ambiguity is only reported once the whole // list has been scanned, so an exact match later in the list can win. var matched: ?Arg = null; var ambiguous = false; for (list) |a| { if (!std.mem.startsWith(u8, a.key, input)) continue; if (std.mem.eql(u8, a.key, input)) return a; if (a.unique_index) |index| { if (input.len > index) return a; } if (matched != null) ambiguous = true; matched = a; } if (ambiguous) return error.Ambiguous; return matched orelse error.Unknown;}
pub fn hasParamPrefix(map: *const StringArrayHashMap([]const u8), target: []const u8) bool { const single = [_]Info{.{ .name = target, .description = "", .type_text = "", .optional = .{ .default_value = "" } }}; var it = map.iterator(); while (it.next()) |e| { _ = resolveParam(e.key_ptr.*, &single) catch continue; return true; } return false;}
pub fn findValue(map: *const StringArrayHashMap([]const u8), params: []const Info, canonical: []const u8) []const u8 { var it = map.iterator(); while (it.next()) |e| { _ = resolveParam(e.key_ptr.*, params) catch continue; if (std.mem.startsWith(u8, canonical, e.key_ptr.*)) return e.value_ptr.*; } return "";}