Luna/apps/rm.cpp

49 lines
1.5 KiB
C++
Raw Permalink Normal View History

2023-04-12 16:11:43 +00:00
#include <os/ArgumentParser.h>
2023-09-02 12:46:14 +00:00
#include <os/Directory.h>
#include <os/File.h>
2023-04-13 16:33:43 +00:00
#include <os/FileSystem.h>
2023-04-12 16:11:43 +00:00
2023-09-02 12:46:14 +00:00
Result<void> remove_wrapper(const os::Path& path, bool verbose)
{
TRY(os::FileSystem::remove(path));
if (verbose) os::println("removed '%s'", path.name().chars());
return {};
}
Result<void> remove_tree(const os::Path& path, bool verbose)
{
auto rc = remove_wrapper(path, verbose);
if (!rc.has_error()) return {};
if (rc.error() != ENOTEMPTY) return rc.release_error();
auto dir = TRY(os::Directory::open(path));
Vector<String> entries = TRY(dir->list_names(os::Directory::Filter::ParentAndBase));
for (const auto& entry : entries) { TRY(remove_tree({ dir->fd(), entry.view() }, verbose)); }
return remove_wrapper(path, verbose);
}
2023-04-13 15:04:59 +00:00
Result<int> luna_main(int argc, char** argv)
2023-04-12 16:11:43 +00:00
{
StringView path;
bool recursive;
2023-09-02 12:46:14 +00:00
bool verbose;
2023-04-12 16:11:43 +00:00
os::ArgumentParser parser;
parser.add_description("Remove a path from the file system."_sv);
parser.add_system_program_info("rm"_sv);
2023-04-12 16:11:43 +00:00
parser.add_positional_argument(path, "path"_sv, true);
parser.add_switch_argument(recursive, 'r', "recursive"_sv,
"remove a directory recursively (by default, rm removes only empty directories)"_sv);
2023-09-02 12:46:14 +00:00
parser.add_switch_argument(verbose, 'v', "verbose"_sv, "log every removed file and directory"_sv);
2023-04-12 16:11:43 +00:00
parser.parse(argc, argv);
2023-09-02 12:46:14 +00:00
if (!recursive) TRY(remove_wrapper(path, verbose));
else
2023-09-02 12:46:14 +00:00
TRY(remove_tree(path, verbose));
2023-04-13 15:04:59 +00:00
return 0;
2023-04-12 16:11:43 +00:00
}