|
| 1 | +/* |
| 2 | + * Copyright (c) 2024, Liav A. <[email protected]> |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: BSD-2-Clause |
| 5 | + */ |
| 6 | + |
| 7 | +#include <AK/Function.h> |
| 8 | +#include <AK/StringView.h> |
| 9 | +#include <LibCore/ArgsParser.h> |
| 10 | +#include <LibCore/DirIterator.h> |
| 11 | +#include <LibCore/DirectoryEntry.h> |
| 12 | +#include <LibCore/System.h> |
| 13 | +#include <LibMain/Main.h> |
| 14 | + |
| 15 | +static bool flag_show_unix_posix_file_type = false; |
| 16 | +static bool flag_show_total_count = false; |
| 17 | + |
| 18 | +ErrorOr<int> serenity_main(Main::Arguments arguments) |
| 19 | +{ |
| 20 | + TRY(Core::System::pledge("stdio rpath")); |
| 21 | + |
| 22 | + Vector<StringView> paths; |
| 23 | + |
| 24 | + Core::ArgsParser args_parser; |
| 25 | + args_parser.set_general_help("List Dirent entries in a directory."); |
| 26 | + args_parser.add_option(flag_show_unix_posix_file_type, "Show POSIX names for file types", "posix-names", 'P'); |
| 27 | + args_parser.add_option(flag_show_total_count, "Show total count for each directory being iterated", "total-entries-count", 't'); |
| 28 | + args_parser.add_positional_argument(paths, "Directory to list", "path", Core::ArgsParser::Required::No); |
| 29 | + args_parser.parse(arguments); |
| 30 | + |
| 31 | + if (paths.is_empty()) |
| 32 | + paths.append("."sv); |
| 33 | + |
| 34 | + for (auto& path : paths) { |
| 35 | + Core::DirIterator di(path, Core::DirIterator::NoStat); |
| 36 | + if (di.has_error()) { |
| 37 | + auto error = di.error(); |
| 38 | + warnln("Failed to open {} - {}", path, error); |
| 39 | + return error; |
| 40 | + } |
| 41 | + |
| 42 | + outln("Traversing {}", path); |
| 43 | + size_t count = 0; |
| 44 | + |
| 45 | + Function<StringView(Core::DirectoryEntry::Type)> name_from_directory_entry_type; |
| 46 | + if (flag_show_unix_posix_file_type) |
| 47 | + name_from_directory_entry_type = Core::DirectoryEntry::posix_name_from_directory_entry_type; |
| 48 | + else |
| 49 | + name_from_directory_entry_type = Core::DirectoryEntry::representative_name_from_directory_entry_type; |
| 50 | + |
| 51 | + while (di.has_next()) { |
| 52 | + auto dir_entry = di.next(); |
| 53 | + if (dir_entry.has_value()) { |
| 54 | + outln(" {} (Type: {}, Inode number: {})", |
| 55 | + dir_entry.value().name, |
| 56 | + name_from_directory_entry_type(dir_entry.value().type), |
| 57 | + dir_entry.value().inode_number); |
| 58 | + count++; |
| 59 | + } |
| 60 | + } |
| 61 | + if (flag_show_total_count) |
| 62 | + outln("Directory {} has {} which has being listed during the program runtime", path, count); |
| 63 | + } |
| 64 | + |
| 65 | + return 0; |
| 66 | +} |
0 commit comments