From 09a053a723fdd83752a9370b3cf53a5dd3ebac62 Mon Sep 17 00:00:00 2001 From: Kemal Zebari Date: Mon, 15 Jan 2024 19:46:59 -0800 Subject: [PATCH] cksum: Handle edge case when no file operands are given when printing Given no file operands, POSIX wants us to read from stdin as well as omit "the pathname and its leading " when printing. --- Userland/Utilities/cksum.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Userland/Utilities/cksum.cpp b/Userland/Utilities/cksum.cpp index 4be228cbaa..09f6f4ceda 100644 --- a/Userland/Utilities/cksum.cpp +++ b/Userland/Utilities/cksum.cpp @@ -80,7 +80,22 @@ ErrorOr serenity_main(Main::Arguments arguments) } if (paths.is_empty()) { - paths.append("-"sv); + // The POSIX spec explains that when given no file operands, we should read from stdin and only print the checksum and file size. So let's do + // this here. + auto file_or_error = Core::File::open_file_or_standard_stream("-"sv, Core::File::OpenMode::Read); + auto filepath = "/dev/stdin"sv; + if (file_or_error.is_error()) { + warnln("{}: {}: {}", arguments.strings[0], filepath, file_or_error.error()); + exit(1); + } + + auto file = file_or_error.release_value(); + auto data = build_checksum_data_using_file(file.ptr(), filepath); + + outln("{:08x} {}", data.checksum, data.file_size); + + // We return fail here since build_checksum_data_using_file() may set it to true, indicating problems have occurred. + return fail; } for (auto& path : paths) {