diff --git a/changelog.d/+cli-checked-stdout.feature.md b/changelog.d/+cli-checked-stdout.feature.md new file mode 100644 index 0000000..4dd9784 --- /dev/null +++ b/changelog.d/+cli-checked-stdout.feature.md @@ -0,0 +1 @@ +Add `cli.Stdout` and `cli.writeOut` for checked standard-output writes that report the first write error on standard error and turn a zero exit status into `1`. diff --git a/docs/orgmode/reference/api.org b/docs/orgmode/reference/api.org index 5dc3ac3..238db52 100644 --- a/docs/orgmode/reference/api.org +++ b/docs/orgmode/reference/api.org @@ -94,9 +94,13 @@ Error set: [[zig:zig_common.logs.GzipError]]. | Function | Error set | |----------------------------------------+-----------| +| [[zig:zig_common.cli.Stdout.write]] | none | +| [[zig:zig_common.cli.Stdout.print]] | none | +| [[zig:zig_common.cli.Stdout.finish]] | none | | [[zig:zig_common.cli.put]] | none | | [[zig:zig_common.cli.print]] | none | | [[zig:zig_common.cli.out]] | none | +| [[zig:zig_common.cli.writeOut]] | none | | [[zig:zig_common.cli.err]] | none | | [[zig:zig_common.cli.die]] | none | | [[zig:zig_common.cli.versionLine]] | none | diff --git a/docs/orgmode/reference/cli-conventions.org b/docs/orgmode/reference/cli-conventions.org index 43ca4d5..d1e2814 100644 --- a/docs/orgmode/reference/cli-conventions.org +++ b/docs/orgmode/reference/cli-conventions.org @@ -8,17 +8,20 @@ The messages, exit statuses and version line that the stackhands Zig tools share ** Messages -| Call | Writes | To | -|------------------------------+---------------------------------------------+----------------------| -| [[zig:zig_common.cli.put]] | the bytes as given | the descriptor given | -| [[zig:zig_common.cli.print]] | the arguments, formatted | the descriptor given | -| [[zig:zig_common.cli.out]] | the arguments, formatted | stdout, descriptor 1 | -| [[zig:zig_common.cli.err]] | the arguments, formatted | stderr, descriptor 2 | -| [[zig:zig_common.cli.die]] | =TOOL: message= and a newline, then exits 2 | stderr, descriptor 2 | +| Call | Writes | To | +|--------------------------------------+------------------------------------------------------+----------------------| +| [[zig:zig_common.cli.put]] | the bytes as given | the descriptor given | +| [[zig:zig_common.cli.print]] | the arguments, formatted | the descriptor given | +| [[zig:zig_common.cli.out]] | the arguments, formatted | stdout, descriptor 1 | +| [[zig:zig_common.cli.writeOut]] | the bytes as given, reporting a write failure | stdout, descriptor 1 | +| [[zig:zig_common.cli.Stdout.write]] | the bytes as given, latching the first write failure | stdout, descriptor 1 | +| [[zig:zig_common.cli.Stdout.print]] | the arguments, formatted, latching write failures | stdout, descriptor 1 | +| [[zig:zig_common.cli.err]] | the arguments, formatted | stderr, descriptor 2 | +| [[zig:zig_common.cli.die]] | =TOOL: message= and a newline, then exits 2 | stderr, descriptor 2 | - Only =die= adds a newline. -- A write that fails, as one to a closed stdout or to =/dev/full= does, is ignored: it changes neither what the tool did nor its exit status. -- A message longer than 8 KiB is formatted on the heap; when that allocation fails, nothing is written. +- =put=, =print=, =out= and =err= ignore write errors. When stdout carries what a caller captures or evaluates, [[zig:zig_common.cli.writeOut]] and [[zig:zig_common.cli.Stdout]] check the write, print =TOOL: cannot write output (ERRNO)= on stderr once, and [[zig:zig_common.cli.Stdout.finish]] turns exit status 0 into 1. +- A message longer than 8 KiB is formatted on the heap; when that allocation fails, =print= writes nothing and =Stdout.print= marks output failed. ** Exit status diff --git a/src/cli.zig b/src/cli.zig index 43a517b..99ee866 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -33,6 +33,63 @@ pub fn out(comptime fmt: []const u8, args: anytype) void { print(1, fmt, args); } +const printFd = print; + +/// Checked writer for standard output (`fd` 1 by default) that reports the +/// first write failure on `err_fd` as `"TOOL: cannot write output (ERRNO)"` +/// and remembers the error so later writes stop and exit status `0` becomes +/// `1`. +pub const Stdout = struct { + tool: []const u8, + fd: sys.fd_t = 1, + err_fd: sys.fd_t = 2, + failed: bool = false, + + /// Write `bytes` to `fd`. On the first failure, sets `failed`, writes + /// `"TOOL: cannot write output (ERRNO)\n"` to `err_fd`, and returns + /// `false`; later calls return `false` without repeating the message. + pub fn write(self: *Stdout, bytes: []const u8) bool { + if (self.failed) return false; + sys.writeAll(self.fd, bytes) catch |e| { + self.failed = true; + printFd(self.err_fd, "{s}: cannot write output ({s})\n", .{ self.tool, sys.describe(e) }); + return false; + }; + return true; + } + + /// Format `args` with `fmt` and `write` the text. A message longer than + /// 8 KiB is formatted on the heap; when that allocation fails, sets + /// `failed` and reports out of memory on `err_fd`. + pub fn print(self: *Stdout, comptime fmt: []const u8, args: anytype) bool { + if (self.failed) return false; + var buf: [8192]u8 = undefined; + if (std.mem.print(&buf, fmt, args)) |s| { + return self.write(s); + } else |_| {} + var w: std.Io.Writer.Allocating = .init(std.heap.page_allocator); + defer w.deinit(); + w.writer.print(fmt, args) catch { + self.failed = true; + printFd(self.err_fd, "{s}: cannot write output (out of memory)\n", .{self.tool}); + return false; + }; + return self.write(w.written()); + } + + /// Return `1` when `rc` is `0` and an earlier write failed; otherwise `rc`. + pub fn finish(self: *const Stdout, rc: u8) u8 { + return if (rc == 0 and self.failed) 1 else rc; + } +}; + +/// Write `bytes` to stdout, reporting `"TOOL: cannot write output (ERRNO)"` +/// on stderr and returning `false` when the write fails. +pub fn writeOut(tool: []const u8, bytes: []const u8) bool { + var s: Stdout = .{ .tool = tool }; + return s.write(bytes); +} + /// `print` to stderr. No newline is added. pub fn err(comptime fmt: []const u8, args: anytype) void { print(2, fmt, args); @@ -63,3 +120,102 @@ test "put and print ignore write errors and versionLine formats tool and version try std.testing.expect(std.mem.startsWith(u8, line, "demo 1.2.3 (")); try std.testing.expect(std.mem.endsWith(u8, line, ", abc1234)\n")); } + +test "Stdout and writeOut deliver output and report first write failure once" { + const linux = std.os.linux; + const fsx = @import("fsx.zig"); + const a = std.testing.allocator; + + { + var out_fds: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&out_fds, .{ .CLOEXEC = true }))); + defer sys.close(out_fds[0]); + var err_fds: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&err_fds, .{ .CLOEXEC = true }))); + defer sys.close(err_fds[0]); + + var s: Stdout = .{ .tool = "demo", .fd = out_fds[1], .err_fd = err_fds[1] }; + try std.testing.expect(s.write("hello ")); + try std.testing.expect(s.print("world {d}\n", .{7})); + var big: [9000]u8 = undefined; + @memset(&big, 'a'); + try std.testing.expect(s.print("{s}\n", .{big[0..]})); + sys.close(out_fds[1]); + sys.close(err_fds[1]); + + const got_out = try fsx.readAll(a, out_fds[0], 32 * 1024); + defer a.free(got_out); + const got_err = try fsx.readAll(a, err_fds[0], 4096); + defer a.free(got_err); + try std.testing.expectEqual(@as(usize, 14 + 9001), got_out.len); + try std.testing.expect(std.mem.startsWith(u8, got_out, "hello world 7\naaa")); + try std.testing.expectEqualStrings("", got_err); + try std.testing.expect(!s.failed); + try std.testing.expectEqual(@as(u8, 0), s.finish(0)); + try std.testing.expectEqual(@as(u8, 2), s.finish(2)); + } + + { + var err_fds: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&err_fds, .{ .CLOEXEC = true }))); + defer sys.close(err_fds[0]); + + var s: Stdout = .{ .tool = "eb-local", .fd = -1, .err_fd = err_fds[1] }; + const runNested = struct { + fn call(out_writer: *Stdout) u8 { + _ = out_writer.print("first {d}\n", .{1}); + return 0; + } + }.call; + try std.testing.expectEqual(@as(u8, 1), s.finish(runNested(&s))); + try std.testing.expect(s.failed); + try std.testing.expect(!s.write("second\n")); + try std.testing.expect(!s.print("third {d}\n", .{3})); + sys.close(err_fds[1]); + + const got_err = try fsx.readAll(a, err_fds[0], 4096); + defer a.free(got_err); + try std.testing.expectEqualStrings("eb-local: cannot write output ([Errno 9] Bad file descriptor)\n", got_err); + try std.testing.expectEqual(@as(u8, 1), s.finish(0)); + try std.testing.expectEqual(@as(u8, 2), s.finish(2)); + } + + if (sys.openat(linux.AT.FDCWD, "/dev/full", .{ .ACCMODE = .WRONLY }, 0)) |full_fd| { + defer sys.close(full_fd); + var err_fds: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&err_fds, .{ .CLOEXEC = true }))); + defer sys.close(err_fds[0]); + + var big: [9000]u8 = undefined; + @memset(&big, 'z'); + var s: Stdout = .{ .tool = "eb-local", .fd = full_fd, .err_fd = err_fds[1] }; + try std.testing.expect(!s.print("{s}\n", .{big[0..]})); + try std.testing.expect(!s.write("after\n")); + sys.close(err_fds[1]); + + const got_err = try fsx.readAll(a, err_fds[0], 4096); + defer a.free(got_err); + try std.testing.expectEqualStrings("eb-local: cannot write output ([Errno 28] No space left on device)\n", got_err); + + var child_err: [2]i32 = undefined; + try std.testing.expectEqual(linux.E.SUCCESS, linux.errno(linux.pipe2(&child_err, .{ .CLOEXEC = true }))); + defer sys.close(child_err[0]); + const pid: isize = @bitCast(linux.fork()); + if (pid < 0) return error.TestUnexpectedResult; + if (pid == 0) { + _ = linux.dup2(full_fd, 1); + _ = linux.dup2(child_err[1], 2); + const ok = writeOut("demo", "payload\n"); + linux.exit_group(if (ok) 0 else 1); + } + sys.close(child_err[1]); + var raw: i32 = 0; + while (linux.errno(linux.wait4(@intCast(pid), &raw, 0, null)) == .INTR) {} + const st: u32 = @bitCast(raw); + try std.testing.expect(linux.W.IFEXITED(st)); + try std.testing.expectEqual(@as(u8, 1), linux.W.EXITSTATUS(st)); + const child_msg = try fsx.readAll(a, child_err[0], 4096); + defer a.free(child_msg); + try std.testing.expectEqualStrings("demo: cannot write output ([Errno 28] No space left on device)\n", child_msg); + } else |_| {} +}