ladybird/Userland/Utilities/ln.cpp

57 lines
1.6 KiB
C++
Raw Normal View History

/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/LexicalPath.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/System.h>
2022-06-28 07:59:12 +00:00
ErrorOr<int> serenity_main(Main::Arguments arguments)
{
TRY(Core::System::pledge("stdio cpath rpath"));
2020-02-18 12:21:28 +00:00
2021-10-23 11:52:09 +00:00
bool force = false;
bool symbolic = false;
StringView target;
StringView path;
2019-05-17 13:28:53 +00:00
Core::ArgsParser args_parser;
2021-10-23 11:52:09 +00:00
args_parser.add_option(force, "Force the creation", "force", 'f');
args_parser.add_option(symbolic, "Create a symlink", "symbolic", 's');
args_parser.add_positional_argument(target, "Link target", "target");
args_parser.add_positional_argument(path, "Link path", "path", Core::ArgsParser::Required::No);
2022-06-28 07:59:12 +00:00
args_parser.parse(arguments);
DeprecatedString path_buffer;
if (path.is_empty()) {
path_buffer = LexicalPath::basename(target);
path = path_buffer.view();
}
auto stat = Core::System::lstat(path);
if (stat.is_error() && stat.error().code() != ENOENT)
return stat.release_error();
2021-10-23 11:52:09 +00:00
if (!stat.is_error() && S_ISDIR(stat.value().st_mode)) {
// The target path is a directory, so we presumably want <path>/<filename> as the effective path.
path_buffer = LexicalPath::join(path, LexicalPath::basename(target)).string();
path = path_buffer.view();
stat = Core::System::lstat(path);
}
if (force && !stat.is_error()) {
TRY(Core::System::unlink(path));
}
if (symbolic) {
TRY(Core::System::symlink(target, path));
} else {
TRY(Core::System::link(target, path));
}
return 0;
}