summaryrefslogtreecommitdiff
path: root/Userland/Utilities/rev.cpp
blob: d4cb1cfe526c5ba0fb4dca8c77a8d468968d065e (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
/*
 * Copyright (c) 2021, Thomas Voss <thomasvoss@live.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

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

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

    Vector<String> paths;
    Core::ArgsParser args_parser;

    args_parser.set_general_help("Concatente files to stdout with each line in reverse.");
    args_parser.add_positional_argument(paths, "File path", "path", Core::ArgsParser::Required::No);
    args_parser.parse(argc, argv);

    Vector<RefPtr<Core::File>> files;
    if (paths.is_empty()) {
        files.append(Core::File::standard_input());
    } else {
        for (auto const& path : paths) {
            auto file_or_error = Core::File::open(path, Core::File::ReadOnly);
            if (file_or_error.is_error()) {
                warnln("Failed to open {}: {}", path, file_or_error.error());
                continue;
            }

            files.append(file_or_error.value());
        }
    }

    if (pledge("stdio", nullptr) < 0) {
        perror("pledge");
        return 1;
    }

    for (auto& file : files) {
        while (file->can_read_line()) {
            auto line = file->read_line();
            outln("{}", line.reverse());
        }
    }

    return 0;
}