refactor command processing into its own function

This commit is contained in:
Emil Lerch 2025-09-20 15:46:26 -07:00
parent 78a059e9ef
commit dbeff4b885
Signed by: lobo
GPG key ID: A7B62D657EF764F8

View file

@ -270,11 +270,24 @@ pub fn main() !u8 {
};
defer parser.deinit();
processCommand(allocator, args[1], &parser, &devices) catch |err| {
switch (err) {
error.UnrecognizedSentence => {
try stderr.print("Unrecognized sentence: {s}\n", .{args[1]});
return 1;
},
else => return err,
}
};
return 0;
}
fn processCommand(allocator: std.mem.Allocator, sentence: [:0]const u8, parser: *pos.Parser, devices: *std.StringHashMap([]const u8)) !void {
// Try original sentence first, then with word replacements
const replacement_keys = word_replacements.keys();
const replacement_values = word_replacements.values();
var sentence_to_try: [:0]const u8 = args[1];
var sentence_to_try: [:0]const u8 = sentence;
var replaced_sentence: ?[:0]u8 = null;
defer if (replaced_sentence) |s| allocator.free(s);
@ -339,19 +352,16 @@ pub fn main() !u8 {
std.log.debug("{s}]", .{aw.written()});
if (parseAction(action_words)) |action| {
if (try extractDevice(allocator, object_words, &devices)) |entry| {
if (try extractDevice(allocator, object_words, devices)) |entry| {
try sendWemoCommand(entry, action, allocator);
success = true;
break; // Success, exit
}
}
}
if (!success) {
try stderr.print("Unrecognized sentence: {s}\n", .{args[1]});
return 1;
}
return 0;
if (!success) return error.UnrecognizedSentence;
}
test "extractDevice single word exact match" {
var devices = std.StringHashMap([]const u8).init(std.testing.allocator);
defer devices.deinit();