Directory.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (c) 2022, kleines Filmröllchen <filmroellchen@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Error.h>
  8. #include <AK/Format.h>
  9. #include <AK/LexicalPath.h>
  10. #include <AK/Noncopyable.h>
  11. #include <AK/Optional.h>
  12. #include <LibCore/Stream.h>
  13. #include <dirent.h>
  14. #include <sys/stat.h>
  15. namespace Core {
  16. class DirIterator;
  17. // Deal with real system directories. Any Directory instance always refers to a valid existing directory.
  18. class Directory {
  19. AK_MAKE_NONCOPYABLE(Directory);
  20. public:
  21. Directory(Directory&&);
  22. ~Directory();
  23. // When this flag is set, both the directory attempted to instantiate as well as all of its parents are created with mode 0755 if necessary.
  24. enum class CreateDirectories : bool {
  25. No,
  26. Yes,
  27. };
  28. static ErrorOr<Directory> create(LexicalPath path, CreateDirectories, mode_t creation_mode = 0755);
  29. static ErrorOr<Directory> create(String path, CreateDirectories, mode_t creation_mode = 0755);
  30. static ErrorOr<Directory> adopt_fd(int fd, Optional<LexicalPath> path = {});
  31. ErrorOr<NonnullOwnPtr<Stream::File>> open(StringView filename, Stream::OpenMode mode) const;
  32. ErrorOr<struct stat> stat() const;
  33. ErrorOr<DirIterator> create_iterator() const;
  34. ErrorOr<LexicalPath> path() const;
  35. static ErrorOr<bool> is_valid_directory(int fd);
  36. private:
  37. Directory(int directory_fd, Optional<LexicalPath> path);
  38. static ErrorOr<void> ensure_directory(LexicalPath const& path, mode_t creation_mode = 0755);
  39. Optional<LexicalPath> m_path;
  40. int m_directory_fd;
  41. };
  42. }
  43. namespace AK {
  44. template<>
  45. struct Formatter<Core::Directory> : Formatter<StringView> {
  46. ErrorOr<void> format(FormatBuilder& builder, Core::Directory const& directory)
  47. {
  48. auto path = directory.path();
  49. if (path.is_error())
  50. return Formatter<StringView>::format(builder, "<unknown>");
  51. return Formatter<StringView>::format(builder, path.release_value().string());
  52. }
  53. };
  54. }