summaryrefslogtreecommitdiff
path: root/Userland/rm.cpp
blob: d8e691aa8b3cfb79e0e89bff281035b919e8b964 (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <AK/Vector.h>
#include <LibCore/CArgsParser.h>
#include <LibCore/CDirIterator.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int remove(bool recursive, const char* path)
{
    struct stat path_stat;
    int s = stat(path, &path_stat);
    if (s < 0) {
        perror("stat");
        return 1;
    }

    if (S_ISDIR(path_stat.st_mode) && recursive) {
        DIR* derp = opendir(path);
        if (!derp) {
            return 1;
        }

        while (auto* de = readdir(derp)) {
            if (strcmp(de->d_name, ".") != 0 && strcmp(de->d_name, "..") != 0) {
                StringBuilder builder;
                builder.append(path);
                builder.append('/');
                builder.append(de->d_name);
                int s = remove(true, builder.to_string().characters());
                if (s < 0)
                    return s;
            }
        }
        int s = rmdir(path);
        if (s < 0) {
            perror("rmdir");
            return 1;
        }
    } else {
        int rc = unlink(path);
        if (rc < 0) {
            perror("unlink");
            return 1;
        }
    }
    return 0;
}

int main(int argc, char** argv)
{
    CArgsParser args_parser("rm");
    args_parser.add_arg("r", "Delete directory recursively.");
    args_parser.add_required_single_value("path");

    CArgsParserResult args = args_parser.parse(argc, argv);
    Vector<String> values = args.get_single_values();
    if (values.size() == 0) {
        args_parser.print_usage();
        return 1;
    }

    return remove(args.is_present("r"), values[0].characters());
}