|
12 | 12 | #include <LibFileSystem/FileSystem.h>
|
13 | 13 | #include <LibMain/Main.h>
|
14 | 14 |
|
| 15 | +static bool is_adding_file(Diff::Patch const& patch) |
| 16 | +{ |
| 17 | + return patch.hunks[0].location.old_range.start_line == 0; |
| 18 | +} |
| 19 | + |
| 20 | +static ErrorOr<ByteBuffer> read_content(StringView path_of_file_to_patch, Diff::Patch const& patch) |
| 21 | +{ |
| 22 | + auto file_to_patch_or_error = Core::File::open(path_of_file_to_patch, Core::File::OpenMode::Read); |
| 23 | + |
| 24 | + // Trivial case - no error reading the file. |
| 25 | + if (!file_to_patch_or_error.is_error()) |
| 26 | + return TRY(file_to_patch_or_error.release_value()->read_until_eof()); |
| 27 | + |
| 28 | + auto const& error = file_to_patch_or_error.error(); |
| 29 | + |
| 30 | + // If the patch is adding a file then it is fine for opening the file to error out if it did not exist. |
| 31 | + if (!is_adding_file(patch) || !error.is_errno() || error.code() != ENOENT) |
| 32 | + return file_to_patch_or_error.release_error(); |
| 33 | + |
| 34 | + return ByteBuffer {}; |
| 35 | +} |
| 36 | + |
15 | 37 | static ErrorOr<void> do_patch(StringView path_of_file_to_patch, Diff::Patch const& patch)
|
16 | 38 | {
|
17 |
| - auto file_to_patch = TRY(Core::File::open(path_of_file_to_patch, Core::File::OpenMode::Read)); |
18 |
| - auto content = TRY(file_to_patch->read_until_eof()); |
| 39 | + ByteBuffer content = TRY(read_content(path_of_file_to_patch, patch)); |
19 | 40 | auto lines = StringView(content).lines();
|
20 | 41 |
|
21 | 42 | // Apply patch to a temporary file in case one or more of the hunks fails.
|
@@ -54,7 +75,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
|
54 | 75 | StringView to_patch;
|
55 | 76 | if (FileSystem::is_regular_file(patch.header.old_file_path)) {
|
56 | 77 | to_patch = patch.header.old_file_path;
|
57 |
| - } else if (FileSystem::is_regular_file(patch.header.new_file_path)) { |
| 78 | + } else if (is_adding_file(patch) || FileSystem::is_regular_file(patch.header.new_file_path)) { |
58 | 79 | to_patch = patch.header.new_file_path;
|
59 | 80 | } else {
|
60 | 81 | warnln("Unable to determine file to patch");
|
|
0 commit comments