From de1726caee9143c07bb2d43b69e4dcd772353b5f Mon Sep 17 00:00:00 2001 From: Andrew Kaster Date: Fri, 4 Aug 2023 08:57:15 -0600 Subject: [PATCH] BindingsGenerator: Only truncate generated files if they have changed Rework the write_if_changed logic to properly truncate the output file. The original logic would not truncate the file, leading to extra junk at the end of files if the IDL files shrunk between builds. --- .../LibWeb/BindingsGenerator/main.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/main.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/main.cpp index 5157d053f9..53ce776838 100644 --- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/main.cpp +++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/main.cpp @@ -128,13 +128,18 @@ ErrorOr serenity_main(Main::Arguments arguments) auto write_if_changed = [&](auto generator_function, StringView file_path) -> ErrorOr { (*generator_function)(interface, output_builder); - auto output_file = TRY(Core::File::open(file_path, Core::File::OpenMode::ReadWrite | Core::File::OpenMode::Truncate)); + auto current_file_or_error = Core::File::open(file_path, Core::File::OpenMode::Read); + if (current_file_or_error.is_error() && current_file_or_error.error().code() != ENOENT) + return current_file_or_error.release_error(); + ByteBuffer current_contents; + if (!current_file_or_error.is_error()) + current_contents = TRY(current_file_or_error.value()->read_until_eof()); // Only write to disk if contents have changed - auto previous_contents = TRY(output_file->read_until_eof()); - TRY(output_file->seek(0, SeekMode::SetPosition)); - if (previous_contents != output_builder.string_view().bytes()) + if (current_contents != output_builder.string_view().bytes()) { + auto output_file = TRY(Core::File::open(file_path, Core::File::OpenMode::Write | Core::File::OpenMode::Truncate)); TRY(output_file->write_until_depleted(output_builder.string_view().bytes())); + } // FIXME: Can we add clear_with_capacity to StringBuilder instead of throwing away the allocated buffer? output_builder.clear(); return {};