ladybird/Userland/Utilities/gunzip.cpp

71 lines
2.3 KiB
C++
Raw Normal View History

2020-08-28 17:54:49 +02:00
/*
* Copyright (c) 2020, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
2020-08-28 17:54:49 +02:00
*/
#include <LibCompress/Gzip.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/FileStream.h>
2022-01-13 21:24:28 +01:00
#include <LibCore/System.h>
#include <LibMain/Main.h>
#include <unistd.h>
2020-08-28 17:54:49 +02:00
static bool decompress_file(Buffered<Core::InputFileStream>& input_stream, Buffered<Core::OutputFileStream>& output_stream)
2020-08-28 17:54:49 +02:00
{
auto gzip_stream = Compress::GzipDecompressor { input_stream };
u8 buffer[4096];
while (!gzip_stream.has_any_error() && !gzip_stream.unreliable_eof()) {
2020-08-28 17:54:49 +02:00
const auto nread = gzip_stream.read({ buffer, sizeof(buffer) });
output_stream.write_or_error({ buffer, nread });
}
return !gzip_stream.handle_any_error();
2020-08-28 17:54:49 +02:00
}
2022-01-13 21:24:28 +01:00
ErrorOr<int> serenity_main(Main::Arguments args)
2020-08-28 17:54:49 +02:00
{
Vector<StringView> filenames;
2020-08-28 17:54:49 +02:00
bool keep_input_files { false };
bool write_to_stdout { false };
Core::ArgsParser args_parser;
args_parser.add_option(keep_input_files, "Keep (don't delete) input files", "keep", 'k');
args_parser.add_option(write_to_stdout, "Write to stdout, keep original files unchanged", "stdout", 'c');
args_parser.add_positional_argument(filenames, "File to decompress", "FILE");
2022-01-13 21:24:28 +01:00
args_parser.parse(args);
2020-08-28 17:54:49 +02:00
if (write_to_stdout)
keep_input_files = true;
for (auto filename : filenames) {
if (!filename.ends_with(".gz"))
filename = String::formatted("{}.gz", filename);
2020-08-28 17:54:49 +02:00
const auto input_filename = filename;
const auto output_filename = filename.substring_view(0, filename.length() - 3);
2022-01-13 21:24:28 +01:00
auto input_stream_result = TRY(Core::InputFileStream::open_buffered(input_filename));
auto success = false;
2020-08-28 17:54:49 +02:00
if (write_to_stdout) {
2020-09-02 17:12:53 +02:00
auto stdout = Core::OutputFileStream::stdout_buffered();
2022-01-13 21:24:28 +01:00
success = decompress_file(input_stream_result, stdout);
2020-08-28 17:54:49 +02:00
} else {
2022-01-13 21:24:28 +01:00
auto output_stream_result = TRY(Core::OutputFileStream::open_buffered(output_filename));
success = decompress_file(input_stream_result, output_stream_result);
}
if (!success) {
warnln("Failed gzip decompressing input file");
return 1;
2020-08-28 17:54:49 +02:00
}
2022-01-13 21:24:28 +01:00
if (!keep_input_files)
TRY(Core::System::unlink(input_filename));
2020-08-28 17:54:49 +02:00
}
return 0;
2020-08-28 17:54:49 +02:00
}