~jan0sch/rig

Showing details for patch e3ed0571503626b9c29f782610ec09bba6379726.
2025-04-12 (Sat), 5:43 PM - Jens Grassel - e3ed0571503626b9c29f782610ec09bba6379726

Refactoring: make cli arguments cross platform compatible

Summary of changes
1 files modified with 30 lines added and 13 lines removed
  • src/main.zig with 30 added and 13 removed lines
diff -rN -u old-rig/src/main.zig new-rig/src/main.zig
--- old-rig/src/main.zig	2025-04-19 12:35:39.533577073 +0000
+++ new-rig/src/main.zig	2025-04-19 12:35:39.533577073 +0000
@@ -3,7 +3,7 @@
 const std = @import("std");
 const fs = std.fs;
 
-pub fn main() !void {
+pub fn main() !u8 {
     var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
     defer arena.deinit();
     const allocator = arena.allocator();
@@ -13,18 +13,13 @@
     var prng = std.rand.DefaultPrng.init(seed);
     const random = prng.random();
 
-    const argv = std.os.argv;
+    const argv = try std.process.argsAlloc(allocator);
+    defer std.process.argsFree(allocator, argv);
 
-    if (argv.len > 2) {
-        std.debug.print("Usage: {s} [country code]\n", .{argv[0]});
-        return;
-    }
-
-    var country: [:0]const u8 = "deu";
-    if (argv.len == 2) {
-        const country_arg = argv[1];
-        country = std.mem.span(country_arg);
-    }
+    const country = parseArguments(argv) catch |e| {
+        printHelp(argv);
+        return e;
+    };
 
     const global_path = "/usr/local/share/rig";
     const home = std.posix.getenv("HOME");
@@ -74,6 +69,8 @@
     try stdout.print("{s} {s}, {s}\n", .{ random_forename, random_surname, random_address });
 
     try bw.flush(); // don't forget to flush!
+
+    return 0;
 }
 
 fn calculateRandomEntry(random: std.Random, max: u32) u32 {
@@ -81,6 +78,26 @@
     return result;
 }
 
+/// Parse the given command line arguments and return the needed ones
+/// or an error.
+fn parseArguments(argv: [][]u8) error{ InvalidArgs, MissingArgs }![]const u8 {
+    if (argv.len < 2) {
+        return error.MissingArgs;
+    }
+
+    if (argv[1].len != 3 or argv.len > 2) {
+        return error.InvalidArgs;
+    }
+
+    return argv[1];
+}
+
+/// Print the help for the program.
+fn printHelp(argv: [][]u8) void {
+    std.debug.print("Usage: {s} <ISO-3166-1 alpha-3 country code>\n", .{argv[0]});
+    return;
+}
+
 /// Try to return the content of a file by trying to read it from the given
 /// path and fall back to the alternate one if the first read fails.
 fn readData(allocator: std.mem.Allocator, path: []const u8, alternate_path: []const u8) !std.ArrayList([]const u8) {