serenity/Userland/Utilities/rm.cpp

58 lines
1.8 KiB
C++
Raw Normal View History

/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
2019-06-02 16:04:18 -07:00
#include <AK/StringBuilder.h>
#include <AK/Vector.h>
#include <LibCore/ArgsParser.h>
2021-02-21 02:55:06 +02:00
#include <LibCore/File.h>
2022-01-24 20:58:47 -05:00
#include <LibCore/System.h>
#include <LibMain/Main.h>
#include <stdio.h>
#include <unistd.h>
2022-01-24 20:58:47 -05:00
ErrorOr<int> serenity_main(Main::Arguments arguments)
2019-06-02 16:04:18 -07:00
{
2022-01-24 20:58:47 -05:00
TRY(Core::System::pledge("stdio rpath cpath"));
2020-02-18 13:23:32 +01:00
bool recursive = false;
2020-08-11 13:15:15 +02:00
bool force = false;
2020-11-16 20:39:30 -05:00
bool verbose = false;
bool no_preserve_root = false;
Vector<StringView> paths;
2019-06-02 16:04:18 -07:00
Core::ArgsParser args_parser;
args_parser.add_option(recursive, "Delete directories recursively", "recursive", 'r');
2020-08-11 13:15:15 +02:00
args_parser.add_option(force, "Force", "force", 'f');
2020-11-16 20:39:30 -05:00
args_parser.add_option(verbose, "Verbose", "verbose", 'v');
args_parser.add_option(no_preserve_root, "Do not consider '/' specially", "no-preserve-root", 0);
args_parser.add_positional_argument(paths, "Path(s) to remove", "path", Core::ArgsParser::Required::No);
2022-01-24 20:58:47 -05:00
args_parser.parse(arguments);
2019-06-02 16:04:18 -07:00
if (!force && paths.is_empty()) {
2022-01-24 20:58:47 -05:00
args_parser.print_usage(stderr, arguments.argv[0]);
return 1;
}
2021-02-21 02:55:06 +02:00
bool had_errors = false;
for (auto& path : paths) {
if (!no_preserve_root && path == "/") {
warnln("rm: '/' is protected, try with --no-preserve-root to override this behavior");
continue;
}
2021-02-21 02:55:06 +02:00
auto result = Core::File::remove(path, recursive ? Core::File::RecursionMode::Allowed : Core::File::RecursionMode::Disallowed, force);
if (result.is_error()) {
warnln("rm: cannot remove '{}': {}", path, static_cast<Error const&>(result.error()));
2021-02-21 02:55:06 +02:00
had_errors = true;
}
if (verbose)
outln("removed '{}'", path);
}
2021-02-21 02:55:06 +02:00
return had_errors ? 1 : 0;
2019-06-02 16:04:18 -07:00
}