From 9d33e22ae0348e55f29367f8a3dafd92aa40d19c Mon Sep 17 00:00:00 2001 From: apio Date: Wed, 26 Apr 2023 20:58:04 +0200 Subject: [PATCH] apps: Add base64 --- apps/CMakeLists.txt | 1 + apps/base64.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 apps/base64.cpp diff --git a/apps/CMakeLists.txt b/apps/CMakeLists.txt index 05b1989d..edecfa4e 100644 --- a/apps/CMakeLists.txt +++ b/apps/CMakeLists.txt @@ -25,3 +25,4 @@ luna_app(mkdir.cpp mkdir OFF) luna_app(rm.cpp rm OFF) luna_app(stat.cpp stat OFF) luna_app(uname.cpp uname OFF) +luna_app(base64.cpp base64 OFF) diff --git a/apps/base64.cpp b/apps/base64.cpp new file mode 100644 index 00000000..d8fbd57f --- /dev/null +++ b/apps/base64.cpp @@ -0,0 +1,41 @@ +#include +#include +#include + +Result luna_main(int argc, char** argv) +{ + StringView path; + bool decode { false }; + bool allow_garbage { false }; + + os::ArgumentParser parser; + parser.add_description("Encode or decode Base64 data. If not given a file, reads from standard input."); + parser.add_positional_argument(path, "file", "-"_sv); + parser.add_switch_argument(decode, 'd', "decode", "decode data"); + parser.add_switch_argument(allow_garbage, ' ', "allow-garbage", "ignore non-base64 characters"); + parser.parse(argc, argv); + + auto file = TRY(os::File::open_input_file(path)); + + auto output = os::File::standard_output(); + + if (!decode) + { + auto data = TRY(file->read_all()); + + auto encoded = TRY(Base64::encode(data)); + + output->write(encoded.view()); + output->write("\n"_sv); + } + else + { + auto data = TRY(file->read_all_as_string()); + + auto decoded = TRY(Base64::decode(data.view(), allow_garbage)); + + output->write(decoded); + } + + return 0; +}