summaryrefslogtreecommitdiff
path: root/Userland/Utilities/rm.cpp
blob: c1650aa12b9b9f2321fcd5059f6d8df6dc54b416 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/StringBuilder.h>
#include <AK/Vector.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/File.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char** argv)
{
    if (pledge("stdio rpath cpath", nullptr) < 0) {
        perror("pledge");
        return 1;
    }

    bool recursive = false;
    bool force = false;
    bool verbose = false;
    Vector<const char*> paths;

    Core::ArgsParser args_parser;
    args_parser.add_option(recursive, "Delete directories recursively", "recursive", 'r');
    args_parser.add_option(force, "Force", "force", 'f');
    args_parser.add_option(verbose, "Verbose", "verbose", 'v');
    args_parser.add_positional_argument(paths, "Path(s) to remove", "path", Core::ArgsParser::Required::No);
    args_parser.parse(argc, argv);

    if (!force && paths.is_empty()) {
        args_parser.print_usage(stderr, argv[0]);
        return 1;
    }

    bool had_errors = false;
    for (auto& path : paths) {
        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, result.error().error_code);
            had_errors = true;
        }

        if (verbose)
            outln("removed '{}'", path);
    }
    return had_errors ? 1 : 0;
}