rm.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringBuilder.h>
  7. #include <AK/Vector.h>
  8. #include <LibCore/ArgsParser.h>
  9. #include <LibCore/File.h>
  10. #include <LibCore/System.h>
  11. #include <LibMain/Main.h>
  12. #include <stdio.h>
  13. #include <unistd.h>
  14. ErrorOr<int> serenity_main(Main::Arguments arguments)
  15. {
  16. TRY(Core::System::pledge("stdio rpath cpath"));
  17. bool recursive = false;
  18. bool force = false;
  19. bool verbose = false;
  20. bool no_preserve_root = false;
  21. Vector<StringView> paths;
  22. Core::ArgsParser args_parser;
  23. args_parser.add_option(recursive, "Delete directories recursively", "recursive", 'r');
  24. args_parser.add_option(force, "Ignore nonexistent files", "force", 'f');
  25. args_parser.add_option(verbose, "Verbose", "verbose", 'v');
  26. args_parser.add_option(no_preserve_root, "Do not consider '/' specially", "no-preserve-root", 0);
  27. args_parser.add_positional_argument(paths, "Path(s) to remove", "path", Core::ArgsParser::Required::No);
  28. args_parser.parse(arguments);
  29. if (!force && paths.is_empty()) {
  30. args_parser.print_usage(stderr, arguments.argv[0]);
  31. return 1;
  32. }
  33. bool had_errors = false;
  34. for (auto& path : paths) {
  35. if (!no_preserve_root && path == "/") {
  36. warnln("rm: '/' is protected, try with --no-preserve-root to override this behavior");
  37. continue;
  38. }
  39. auto result = Core::File::remove(path, recursive ? Core::File::RecursionMode::Allowed : Core::File::RecursionMode::Disallowed);
  40. if (result.is_error()) {
  41. auto error = result.release_error();
  42. if (force && error.is_errno() && error.code() == ENOENT)
  43. continue;
  44. warnln("rm: cannot remove '{}': {}", path, error);
  45. had_errors = true;
  46. }
  47. if (verbose)
  48. outln("removed '{}'", path);
  49. }
  50. return had_errors ? 1 : 0;
  51. }