From 9f14073d61f42e92b161ab25b92066f9041d8719 Mon Sep 17 00:00:00 2001 From: Aaron Fischer Date: Wed, 11 Dec 2024 23:42:07 +0100 Subject: [PATCH] Day 11: make things neat Signed-off-by: Aaron Fischer --- src/main.zig | 25 +++++++++++++++++++------ zig-out/bin/entries.log.gmi | 2 ++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/main.zig b/src/main.zig index 3122097..6d5b9cf 100644 --- a/src/main.zig +++ b/src/main.zig @@ -40,7 +40,9 @@ pub fn main() !void { if (eql(u8, firstArg, "list")) { listEntries(); } else if (eql(u8, firstArg, "create")) { - try createNewEntry(); + createNewEntry() catch |err| { + write(Target.Stderr, "error while creating new entry: {any}\n", .{err}); + }; } else { write(Target.Stderr, "Unknown subcommand: {any}\n", .{firstArg}); } @@ -48,7 +50,12 @@ pub fn main() !void { fn createNewEntry() !void { // Open the file in append mode - const file = try std.fs.cwd().openFile("entries.log.gmi", .{ .mode = .read_write }); + const file = std.fs.cwd().openFile("entries.log.gmi", .{ + .mode = .read_write + }) catch |err| { + write(Target.Stderr, "unable to open file: {any}\n", .{err}); + return; + }; defer file.close(); try file.seekFromEnd(0); @@ -65,13 +72,19 @@ fn createNewEntry() !void { // Read the input content from STDIN and append it to the file var buf: [1024]u8 = undefined; - while (try stdin.readUntilDelimiterOrEof(&buf, '\n')) |line| { - try file.writeAll("\n"); - try file.writeAll(date); - try file.writeAll(line); + + try file.writeAll(date); + + while (stdin.readUntilDelimiterOrEof(&buf, '\n')) |line| { + try file.writeAll(line orelse break); try file.writeAll("\n"); + } else |err| { + write(Target.Stderr, "error while reading from stdin: {any}\n", .{err}); + return; } + try file.writeAll("\n"); + // Print some success message and the back link to STDOUT try stdout.print("Entry added successfully\n", .{}); try stdout.print("=> / Back to the log entries", .{}); diff --git a/zig-out/bin/entries.log.gmi b/zig-out/bin/entries.log.gmi index 2446aa4..87769e0 100644 --- a/zig-out/bin/entries.log.gmi +++ b/zig-out/bin/entries.log.gmi @@ -1,5 +1,7 @@ # Server log +=> /create New entry + ## 2024-12-04 23:34 UTC This is a simple entry, with multiple lines of text. This should showcase how this is intended.