diff --git a/src/patch.cpp b/src/patch.cpp index b61ae18..bc725c1 100644 --- a/src/patch.cpp +++ b/src/patch.cpp @@ -590,6 +590,20 @@ int process_patch(const Options& options) Result result = apply_patch(tmp_out_file, reject_writer, input_lines, patch, options, out); + if (result.failed_hunks != 0) { + had_failure = true; + const char* reason = result.was_skipped ? "ignored" : "FAILED"; + inform_hunks_failed(out, reason, patch.hunks, result.failed_hunks); + if (!options.dry_run) { + const auto reject_file = reject_path(options, output_file); + out << " -- saving rejects to file " << reject_file; + + File file(reject_file, mode | std::ios::trunc); + tmp_reject_file.write_entire_contents_to(file); + } + out << '\n'; + } + if (output_to_stdout) { // Nothing else to do other than write to stdout :^) tmp_out_file.write_entire_contents_to(stdout); @@ -600,19 +614,7 @@ int process_patch(const Options& options) write_patched_result_to_file(patch, output_file, permission_result, mode, deferred_writer, tmp_out_file); } - if (result.failed_hunks != 0) { - had_failure = true; - const char* reason = result.was_skipped ? "ignored" : "FAILED"; - inform_hunks_failed(out, reason, patch.hunks, result.failed_hunks); - if (!options.dry_run) { - const auto reject_file = reject_path(options, output_file); - out << " -- saving rejects to file " << reject_file; - - File file(reject_file, mode | std::ios::trunc); - tmp_reject_file.write_entire_contents_to(file); - } - out << '\n'; - } else { + if (result.failed_hunks == 0) { if (!options.dry_run && patch.operation == Operation::Rename) remove_file_and_empty_parent_folders(file_to_patch); diff --git a/tests/test_basic.cpp b/tests/test_basic.cpp index 914e96c..54db5d7 100644 --- a/tests/test_basic.cpp +++ b/tests/test_basic.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: BSD-3-Clause -// Copyright 2022-2023 Shannon Booth +// Copyright 2022-2024 Shannon Booth #include #include @@ -329,6 +329,40 @@ PATCH_TEST(basic_patch_with_dry_run_to_stdout) EXPECT_FILE_EQ("to_patch", to_patch); } +PATCH_TEST(failed_patch_to_stdout) +{ + const std::string patch = R"(--- 1 2022-06-26 12:22:22.161398905 +1200 ++++ 2 2022-06-26 12:22:44.105278030 +1200 +@@ -1,3 +1,2 @@ + 1 +-2 + 3 +)"; + { + Patch::File file("diff.patch", std::ios_base::out); + file << patch; + file.close(); + } + + std::string to_patch = "a\nb\nc\n"; + { + Patch::File file("1", std::ios_base::out); + file << to_patch; + file.close(); + } + + Process process(patch_path, { patch_path, "-i", "diff.patch", "-o", "-", "--force", nullptr }); + + EXPECT_EQ(process.stdout_data(), to_patch); + EXPECT_EQ(process.stderr_data(), R"(patching file - (read from 1) +Hunk #1 FAILED at 1. +1 out of 1 hunk FAILED -- saving rejects to file -.rej +)"); + EXPECT_EQ(process.return_code(), 1); + EXPECT_FILE_EQ("1", to_patch); + EXPECT_FILE_EQ("-.rej", patch); +} + PATCH_TEST(failed_patch_dry_run) { {