From a4e50deeea53f5747a8184ca44bcde1ab895343a Mon Sep 17 00:00:00 2001 From: Shannon Booth Date: Tue, 27 Jun 2023 20:55:50 +1200 Subject: [PATCH] LibDiff: Add Diff::write_unified for formatting unified hunks --- Userland/Libraries/LibDiff/Format.cpp | 21 +++++++++++++++++++++ Userland/Libraries/LibDiff/Format.h | 1 + 2 files changed, 22 insertions(+) diff --git a/Userland/Libraries/LibDiff/Format.cpp b/Userland/Libraries/LibDiff/Format.cpp index 353b606017..996b56079b 100644 --- a/Userland/Libraries/LibDiff/Format.cpp +++ b/Userland/Libraries/LibDiff/Format.cpp @@ -24,6 +24,27 @@ DeprecatedString generate_only_additions(StringView text) return builder.to_deprecated_string(); } +ErrorOr write_unified(Hunk const& hunk, Stream& stream, ColorOutput color_output) +{ + TRY(stream.write_formatted("{}\n", hunk.location)); + + if (color_output == ColorOutput::Yes) { + for (auto const& line : hunk.lines) { + if (line.operation == Line::Operation::Addition) + TRY(stream.write_formatted("\033[32;1m{}\033[0m\n", line)); + else if (line.operation == Line::Operation::Removal) + TRY(stream.write_formatted("\033[31;1m{}\033[0m\n", line)); + else + TRY(stream.write_formatted("{}\n", line)); + } + } else { + for (auto const& line : hunk.lines) + TRY(stream.write_formatted("{}\n", line)); + } + + return {}; +} + ErrorOr write_normal(Hunk const& hunk, Stream& stream, ColorOutput color_output) { // Source line(s) diff --git a/Userland/Libraries/LibDiff/Format.h b/Userland/Libraries/LibDiff/Format.h index f221b84e9f..0ae15ed258 100644 --- a/Userland/Libraries/LibDiff/Format.h +++ b/Userland/Libraries/LibDiff/Format.h @@ -20,6 +20,7 @@ enum class ColorOutput { No, }; +ErrorOr write_unified(Hunk const& hunk, Stream& stream, ColorOutput color_output = ColorOutput::No); ErrorOr write_normal(Hunk const& hunk, Stream& stream, ColorOutput color_output = ColorOutput::No); }