diff --git a/src/main.zig b/src/main.zig index a072ac4..3122097 100644 --- a/src/main.zig +++ b/src/main.zig @@ -3,27 +3,46 @@ const builtin = @import("builtin"); const eql = @import("std").mem.eql; const stdout = std.io.getStdOut().writer(); +const stderr = std.io.getStdErr().writer(); const stdin = std.io.getStdIn().reader(); +const Target = enum { + Stdout, + Stderr, +}; + +pub fn write(target: Target, comptime format: []const u8, args: anytype) void { + switch (target) { + Target.Stdout => stdout.print(format, args) catch |err| { + std.debug.panic("unable to write to output: {any}\n", .{err}); + }, + Target.Stderr => stderr.print(format, args) catch |err| { + std.debug.panic("unable to write to output: {any}\n", .{err}); + }, + } +} + pub fn main() !void { // Read the first argument to determine the subcommand const allocator = std.heap.page_allocator; - var args = try std.process.argsWithAllocator(allocator); + var args = std.process.argsWithAllocator(allocator) catch |err| { + write(Target.Stderr, "out of memory: {any}\n", .{err}); + }; defer args.deinit(); _ = args.next(); // Skip the first argument, which is the program name const firstArg = args.next() orelse { - try stdout.print("No subcommand provided\n", .{}); + write(Target.Stderr, "no subcommand provided\n", .{}); return; }; if (eql(u8, firstArg, "list")) { - try listEntries(); + listEntries(); } else if (eql(u8, firstArg, "create")) { try createNewEntry(); } else { - try stdout.print("Unknown subcommand: {s}\n", .{firstArg}); + write(Target.Stderr, "Unknown subcommand: {any}\n", .{firstArg}); } } @@ -58,16 +77,22 @@ fn createNewEntry() !void { try stdout.print("=> / Back to the log entries", .{}); } -fn listEntries() !void { - const file = try std.fs.cwd().openFile("entries.log.gmi", .{}); +fn listEntries() void { + const file = std.fs.cwd().openFile("entries.log.gmi", .{}) catch |err| { + write(Target.Stderr, "unable to open file: {any}\n", .{err}); + return; + }; defer file.close(); var bufReader = std.io.bufferedReader(file.reader()); var inStream = bufReader.reader(); var buf: [1024]u8 = undefined; - while (try inStream.readUntilDelimiterOrEof(&buf, '\n')) |line| { - try stdout.print("{s}\n", .{ line }); + + while (inStream.readUntilDelimiterOrEof(&buf, '\n')) |line| { + write(Target.Stdout, "{s}\n", .{ line orelse break }); + } else |err| { + write(Target.Stderr, "error while reading the file: {!}\n", .{err}); } }