summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibCore/Directory.h
diff options
context:
space:
mode:
authorkleines Filmröllchen <filmroellchen@serenityos.org>2022-04-10 18:28:43 +0200
committerAndreas Kling <kling@serenityos.org>2022-04-11 00:08:48 +0200
commit46b76f2f55f61f45fc292f800ba2a4e2a5c354be (patch)
tree0f0564f6b4a90e226efddffa669e4a552a5c5c81 /Userland/Libraries/LibCore/Directory.h
parentceba27c3fec888d2ef95251fcd6754f4155175f8 (diff)
downloadserenity-46b76f2f55f61f45fc292f800ba2a4e2a5c354be.zip
LibCore: Introduce Directory
Core::Directory represents an existing directory on the system, and it holds an actual file descriptor so that the user can be sure the directory stays in existence.
Diffstat (limited to 'Userland/Libraries/LibCore/Directory.h')
-rw-r--r--Userland/Libraries/LibCore/Directory.h70
1 files changed, 70 insertions, 0 deletions
diff --git a/Userland/Libraries/LibCore/Directory.h b/Userland/Libraries/LibCore/Directory.h
new file mode 100644
index 0000000000..950a93bb9c
--- /dev/null
+++ b/Userland/Libraries/LibCore/Directory.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2022, kleines Filmröllchen <filmroellchen@serenityos.org>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Error.h>
+#include <AK/Format.h>
+#include <AK/LexicalPath.h>
+#include <AK/Noncopyable.h>
+#include <AK/Optional.h>
+#include <LibCore/Stream.h>
+#include <dirent.h>
+#include <sys/stat.h>
+
+namespace Core {
+
+class DirIterator;
+
+// Deal with real system directories. Any Directory instance always refers to a valid existing directory.
+class Directory {
+ AK_MAKE_NONCOPYABLE(Directory);
+
+public:
+ Directory(Directory&&);
+ ~Directory();
+
+ // 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.
+ enum class CreateDirectories : bool {
+ No,
+ Yes,
+ };
+
+ static ErrorOr<Directory> create(LexicalPath path, CreateDirectories);
+ static ErrorOr<Directory> create(String path, CreateDirectories);
+ static ErrorOr<Directory> adopt_fd(int fd, Optional<LexicalPath> path = {});
+
+ ErrorOr<NonnullOwnPtr<Stream::File>> open(StringView filename, Stream::OpenMode mode) const;
+ ErrorOr<struct stat> stat() const;
+ ErrorOr<DirIterator> create_iterator() const;
+
+ ErrorOr<LexicalPath> path() const;
+
+ static ErrorOr<bool> is_valid_directory(int fd);
+
+private:
+ Directory(int directory_fd, Optional<LexicalPath> path);
+ static ErrorOr<void> ensure_directory(LexicalPath const& path);
+
+ Optional<LexicalPath> m_path;
+ int m_directory_fd;
+};
+
+}
+
+namespace AK {
+template<>
+struct Formatter<Core::Directory> : Formatter<StringView> {
+ ErrorOr<void> format(FormatBuilder& builder, Core::Directory const& directory)
+ {
+ auto path = directory.path();
+ if (path.is_error())
+ return Formatter<StringView>::format(builder, "<unknown>");
+ return Formatter<StringView>::format(builder, path.release_value().string());
+ }
+};
+
+}