From e79ef6461a2983985a94e6447418e9453487e212 Mon Sep 17 00:00:00 2001 From: Sam Atkins Date: Sun, 20 Jun 2021 19:44:10 +0100 Subject: cp: Copy sources into destination if it is already a directory Previously, copying a file to a directory, like this: ```cp README.md Desktop``` correctly copied it to Desktop/README.md, but would fail if the source was also a directory, for example: ```cp -R Documents Desktop``` Now, that correctly copies it to Desktop/Documents, as you would expect. :^) --- Userland/Utilities/cp.cpp | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) (limited to 'Userland') diff --git a/Userland/Utilities/cp.cpp b/Userland/Utilities/cp.cpp index c0ca9a96fc..86a08e6877 100644 --- a/Userland/Utilities/cp.cpp +++ b/Userland/Utilities/cp.cpp @@ -4,6 +4,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include #include #include #include @@ -19,21 +20,27 @@ int main(int argc, char** argv) bool link = false; bool recursion_allowed = false; bool verbose = false; - Vector sources; - const char* destination = nullptr; + Vector sources; + String destination; Core::ArgsParser args_parser; args_parser.add_option(link, "Link files instead of copying", "link", 'l'); args_parser.add_option(recursion_allowed, "Copy directories recursively", "recursive", 'R'); args_parser.add_option(recursion_allowed, "Same as -R", nullptr, 'r'); args_parser.add_option(verbose, "Verbose", "verbose", 'v'); - args_parser.add_positional_argument(sources, "Source file path", "source"); + args_parser.add_positional_argument(sources, "Source file paths", "source"); args_parser.add_positional_argument(destination, "Destination file path", "destination"); args_parser.parse(argc, argv); + bool destination_is_existing_dir = Core::File::is_directory(destination); + for (auto& source : sources) { + auto destination_path = destination_is_existing_dir + ? String::formatted("{}/{}", destination, LexicalPath(source).basename()) + : destination; + auto result = Core::File::copy_file_or_directory( - destination, source, + destination_path, source, recursion_allowed ? Core::File::RecursionMode::Allowed : Core::File::RecursionMode::Disallowed, link ? Core::File::LinkMode::Allowed : Core::File::LinkMode::Disallowed, Core::File::AddDuplicateFileMarker::No); @@ -42,12 +49,12 @@ int main(int argc, char** argv) if (result.error().tried_recursing) warnln("cp: -R not specified; omitting directory '{}'", source); else - warnln("cp: unable to copy '{}': {}", source, result.error().error_code); + warnln("cp: unable to copy '{}' to '{}': {}", source, destination_path, result.error().error_code); return 1; } if (verbose) - outln("'{}' -> '{}'", source, destination); + outln("'{}' -> '{}'", source, destination_path); } return 0; } -- cgit v1.2.3