1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-14 09:24:57 +00:00

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. :^)
This commit is contained in:
Sam Atkins 2021-06-20 19:44:10 +01:00 committed by Andreas Kling
parent ac9003bb70
commit e79ef6461a

View file

@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/LexicalPath.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/File.h>
#include <stdio.h>
@ -19,21 +20,27 @@ int main(int argc, char** argv)
bool link = false;
bool recursion_allowed = false;
bool verbose = false;
Vector<const char*> sources;
const char* destination = nullptr;
Vector<String> 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;
}