From 8f452fdd78cccc27e6ed3b7d2697d4d906177a30 Mon Sep 17 00:00:00 2001 From: Elara6331 Date: Wed, 13 Dec 2023 22:16:57 -0800 Subject: [PATCH] Allow gpioinfo to accept a chip number rather than the whole name --- src/cmd/info.zig | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/cmd/info.zig b/src/cmd/info.zig index bb3c651..98cd0a4 100644 --- a/src/cmd/info.zig +++ b/src/cmd/info.zig @@ -13,8 +13,21 @@ pub fn main() !void { _ = args.skip(); // Skip the program name // Iterate over each argument - while (args.next()) |arg| { - const fl = try dir.openFileZ(arg, .{}); + while (args.next()) |argument| { + const hasGpiochip = hasPrefix(argument, "gpiochip"); + + // If the argument has the "gpiochip" prefix, + // just use it unchanged. Otherwise, add the prefix. + var filename: []const u8 = if (hasGpiochip) + argument + else + try std.mem.concat(alloc, u8, &.{ "gpiochip", argument }); + + // We only need to free if we actually allocated, + // which only happens if there was no prefix. + defer if (!hasGpiochip) alloc.free(filename); + + const fl = try dir.openFile(filename, .{}); var chip = try gpio.getChipByFd(fl.handle); defer chip.close(); // This will close the fd @@ -52,3 +65,8 @@ pub fn main() !void { } } } + +fn hasPrefix(s: []const u8, prefix: []const u8) bool { + if (s.len < prefix.len) return false; + return (std.mem.eql(u8, s[0..prefix.len], prefix)); +}