fix: print help text instead of segfaulting when run without arguments

Fixes #3.
This commit was merged in pull request #4.
This commit is contained in:
2023-10-14 10:41:22 +02:00
parent 4555dc1ef8
commit 36cd54170e

View File

@@ -8,15 +8,26 @@ pub fn main() !void {
var area = heap.ArenaAllocator.init(gpa.allocator());
defer area.deinit();
const help_text = "usage: sp <word>\n\t<word> is the word to check with ispell\n\t<word> can also be piped instead\n";
const allocator = area.allocator();
const stdin = std.io.getStdIn().reader();
const stat = try std.io.getStdIn().stat();
var word: []const u8 = undefined;
// prepare for writing output to stdout
const stdout_file = std.io.getStdOut().writer();
var bw = std.io.bufferedWriter(stdout_file);
const stdout_writer = bw.writer();
switch (stat.kind) {
.named_pipe => {
if (try stdin.readUntilDelimiterOrEofAlloc(allocator, '\n', 1024)) |input| {
word = input;
} else {
_ = try stdout_writer.write(help_text); // output help
try bw.flush(); // don't forget to flush!
os.exit(1);
}
},
else => {
@@ -26,6 +37,10 @@ pub fn main() !void {
const next = arg_iterator.next();
if (next) |input| {
word = input;
} else {
_ = try stdout_writer.write(help_text); // output help
try bw.flush(); // don't forget to flush!
os.exit(1);
}
},
}
@@ -71,11 +86,6 @@ pub fn main() !void {
std.mem.copy(u8, content, output[start_idx .. output.len - 1]);
defer allocator.free(content);
// prepare for writing output to stdout
const stdout_file = std.io.getStdOut().writer();
var bw = std.io.bufferedWriter(stdout_file);
const stdout_writer = bw.writer();
if (content[0] == '*' or content[0] == '+') {
// given word was correct so just return the input as no replacement is necessary
try stdout_writer.print("{s}", .{word});