1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 06:27:45 +00:00

rm: Implement a basic -f mode

This commit is contained in:
Andreas Kling 2020-08-11 13:15:15 +02:00
parent 5bca49162c
commit 2a765ad062

View file

@ -35,35 +35,37 @@
#include <sys/stat.h> #include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
int remove(bool recursive, String path) int remove(bool recursive, bool force, String path)
{ {
struct stat path_stat; struct stat path_stat;
if (lstat(path.characters(), &path_stat) < 0) { if (lstat(path.characters(), &path_stat) < 0) {
perror("lstat"); if (!force)
perror("lstat");
return 1; return 1;
} }
if (S_ISDIR(path_stat.st_mode) && recursive) { if (S_ISDIR(path_stat.st_mode) && recursive) {
auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir); auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir);
if (di.has_error()) { if (di.has_error()) {
fprintf(stderr, "DirIterator: %s\n", di.error_string()); if (!force)
fprintf(stderr, "DirIterator: %s\n", di.error_string());
return 1; return 1;
} }
while (di.has_next()) { while (di.has_next()) {
int s = remove(true, di.next_full_path()); int s = remove(true, force, di.next_full_path());
if (s != 0) if (s != 0 && !force)
return s; return s;
} }
int s = rmdir(path.characters()); int s = rmdir(path.characters());
if (s < 0) { if (s < 0 && !force) {
perror("rmdir"); perror("rmdir");
return 1; return 1;
} }
} else { } else {
int rc = unlink(path.characters()); int rc = unlink(path.characters());
if (rc < 0) { if (rc < 0 && !force) {
perror("unlink"); perror("unlink");
return 1; return 1;
} }
@ -79,16 +81,18 @@ int main(int argc, char** argv)
} }
bool recursive = false; bool recursive = false;
bool force = false;
Vector<const char*> paths; Vector<const char*> paths;
Core::ArgsParser args_parser; Core::ArgsParser args_parser;
args_parser.add_option(recursive, "Delete directories recursively", "recursive", 'r'); args_parser.add_option(recursive, "Delete directories recursively", "recursive", 'r');
args_parser.add_option(force, "Force", "force", 'f');
args_parser.add_positional_argument(paths, "Path(s) to remove", "path"); args_parser.add_positional_argument(paths, "Path(s) to remove", "path");
args_parser.parse(argc, argv); args_parser.parse(argc, argv);
int rc = 0; int rc = 0;
for (auto& path : paths) { for (auto& path : paths) {
rc |= remove(recursive, path); rc |= remove(recursive, force, path);
} }
return rc; return rc;
} }