zargs/examples/file_processor.zig

96 lines
2.7 KiB
Zig

const std = @import("std");
const zargs = @import("zargs");
/// Simple file processor configuration
const Config = struct {
input: []const u8 = "input.txt",
output: []const u8 = "output.txt",
verbose: bool = false,
format: Format = .json,
max_size: u32 = 1024,
tags: []const []const u8 = &[_][]const u8{},
pub const Format = enum { json, xml, csv };
pub const meta = .{
.input = .{
.short = 'i',
.help = "Input file path",
},
.output = .{
.short = 'o',
.help = "Output file path",
},
.verbose = .{
.short = 'v',
.help = "Enable verbose output",
},
.format = .{
.help = "Output format",
},
.max_size = .{
.help = "Maximum file size in KB",
},
.tags = .{
.help = "Tags to filter (can specify multiple)",
},
};
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
defer zargs.shutdown();
// Use populate to register metadata and parse arguments
const config = try zargs.parse(Config, allocator);
// Check if help was requested after parsing
if (zargs.isHelp(allocator)) {
// Generate and display help using the registry
const help_text = try zargs.getUsageAlloc(allocator, "file_processor");
defer allocator.free(help_text);
std.debug.print("{s}", .{help_text});
return;
}
// Use the configuration
if (config.verbose) {
std.debug.print("Configuration:\n", .{});
std.debug.print(" Input: {s}\n", .{config.input});
std.debug.print(" Output: {s}\n", .{config.output});
std.debug.print(" Format: {s}\n", .{@tagName(config.format)});
std.debug.print(" Max Size: {} KB\n", .{config.max_size});
if (config.tags.len > 0) {
std.debug.print(" Tags: ", .{});
for (config.tags, 0..) |tag, i| {
if (i > 0) std.debug.print(", ", .{});
std.debug.print("{s}", .{tag});
}
std.debug.print("\n", .{});
}
std.debug.print("\n", .{});
}
// Process the file
std.debug.print("Processing: {s} -> {s} (format: {s})\n", .{
config.input,
config.output,
@tagName(config.format),
});
// Simulate file processing
if (config.tags.len > 0) {
std.debug.print("Filtering by tags: ", .{});
for (config.tags, 0..) |tag, i| {
if (i > 0) std.debug.print(", ", .{});
std.debug.print("{s}", .{tag});
}
std.debug.print("\n", .{});
}
std.debug.print("Done!\n", .{});
}