refactor command processing into its own function
This commit is contained in:
parent
78a059e9ef
commit
dbeff4b885
1 changed files with 17 additions and 7 deletions
24
src/main.zig
24
src/main.zig
|
@ -270,11 +270,24 @@ pub fn main() !u8 {
|
||||||
};
|
};
|
||||||
defer parser.deinit();
|
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
|
// Try original sentence first, then with word replacements
|
||||||
const replacement_keys = word_replacements.keys();
|
const replacement_keys = word_replacements.keys();
|
||||||
const replacement_values = word_replacements.values();
|
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;
|
var replaced_sentence: ?[:0]u8 = null;
|
||||||
defer if (replaced_sentence) |s| allocator.free(s);
|
defer if (replaced_sentence) |s| allocator.free(s);
|
||||||
|
|
||||||
|
@ -339,19 +352,16 @@ pub fn main() !u8 {
|
||||||
std.log.debug("{s}]", .{aw.written()});
|
std.log.debug("{s}]", .{aw.written()});
|
||||||
|
|
||||||
if (parseAction(action_words)) |action| {
|
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);
|
try sendWemoCommand(entry, action, allocator);
|
||||||
success = true;
|
success = true;
|
||||||
break; // Success, exit
|
break; // Success, exit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!success) {
|
if (!success) return error.UnrecognizedSentence;
|
||||||
try stderr.print("Unrecognized sentence: {s}\n", .{args[1]});
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
test "extractDevice single word exact match" {
|
test "extractDevice single word exact match" {
|
||||||
var devices = std.StringHashMap([]const u8).init(std.testing.allocator);
|
var devices = std.StringHashMap([]const u8).init(std.testing.allocator);
|
||||||
defer devices.deinit();
|
defer devices.deinit();
|
||||||
|
|
Loading…
Add table
Reference in a new issue