mirror of
https://github.com/RGBCube/serenity
synced 2025-05-14 09:04:59 +00:00
patch: Support creation of a file
Previously patch would always expect the file that it was patching to exist (even it were empty). If we know that the patch is creating a file from nothing (i.e has a start line of '0'), then we treat a file that doesn't exist as if it has no content lines.
This commit is contained in:
parent
0612e8ec6a
commit
f893e0820f
2 changed files with 40 additions and 3 deletions
|
@ -12,10 +12,31 @@
|
|||
#include <LibFileSystem/FileSystem.h>
|
||||
#include <LibMain/Main.h>
|
||||
|
||||
static bool is_adding_file(Diff::Patch const& patch)
|
||||
{
|
||||
return patch.hunks[0].location.old_range.start_line == 0;
|
||||
}
|
||||
|
||||
static ErrorOr<ByteBuffer> read_content(StringView path_of_file_to_patch, Diff::Patch const& patch)
|
||||
{
|
||||
auto file_to_patch_or_error = Core::File::open(path_of_file_to_patch, Core::File::OpenMode::Read);
|
||||
|
||||
// Trivial case - no error reading the file.
|
||||
if (!file_to_patch_or_error.is_error())
|
||||
return TRY(file_to_patch_or_error.release_value()->read_until_eof());
|
||||
|
||||
auto const& error = file_to_patch_or_error.error();
|
||||
|
||||
// If the patch is adding a file then it is fine for opening the file to error out if it did not exist.
|
||||
if (!is_adding_file(patch) || !error.is_errno() || error.code() != ENOENT)
|
||||
return file_to_patch_or_error.release_error();
|
||||
|
||||
return ByteBuffer {};
|
||||
}
|
||||
|
||||
static ErrorOr<void> do_patch(StringView path_of_file_to_patch, Diff::Patch const& patch)
|
||||
{
|
||||
auto file_to_patch = TRY(Core::File::open(path_of_file_to_patch, Core::File::OpenMode::Read));
|
||||
auto content = TRY(file_to_patch->read_until_eof());
|
||||
ByteBuffer content = TRY(read_content(path_of_file_to_patch, patch));
|
||||
auto lines = StringView(content).lines();
|
||||
|
||||
// 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)
|
|||
StringView to_patch;
|
||||
if (FileSystem::is_regular_file(patch.header.old_file_path)) {
|
||||
to_patch = patch.header.old_file_path;
|
||||
} else if (FileSystem::is_regular_file(patch.header.new_file_path)) {
|
||||
} else if (is_adding_file(patch) || FileSystem::is_regular_file(patch.header.new_file_path)) {
|
||||
to_patch = patch.header.new_file_path;
|
||||
} else {
|
||||
warnln("Unable to determine file to patch");
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue