Allow gpioinfo to accept a chip number rather than the whole name

This commit is contained in:
Elara 2023-12-13 22:16:57 -08:00
parent 3adc525084
commit 8f452fdd78

View File

@ -13,8 +13,21 @@ pub fn main() !void {
_ = args.skip(); // Skip the program name _ = args.skip(); // Skip the program name
// Iterate over each argument // Iterate over each argument
while (args.next()) |arg| { while (args.next()) |argument| {
const fl = try dir.openFileZ(arg, .{}); 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); var chip = try gpio.getChipByFd(fl.handle);
defer chip.close(); // This will close the fd 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));
}