summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--cabinet/magic.cpp29
-rw-r--r--cabinet/magic.hpp6
-rw-r--r--cabinet/main.cpp2
3 files changed, 25 insertions, 12 deletions
diff --git a/cabinet/magic.cpp b/cabinet/magic.cpp
index 08b3046..96b78a3 100644
--- a/cabinet/magic.cpp
+++ b/cabinet/magic.cpp
@@ -53,24 +53,35 @@ namespace cab
return *this;
}
- auto magic::process(std::filesystem::path path) -> std::expected<std::string, std::string>
+ auto magic::process(std::filesystem::path path) -> std::expected<std::string, std::error_code>
{
- auto result = ::magic_file(m_cookie, path.native().c_str());
- if (!result)
+ return handle_result(::magic_file(m_cookie, path.native().c_str()));
+ }
+
+ auto magic::process(int file_descriptor) -> std::expected<std::string, std::error_code>
+ {
+ if (file_descriptor < 0)
{
- return std::unexpected{std::string{::magic_error(m_cookie)}};
+ return std::unexpected{std::make_error_code(std::errc::invalid_argument)};
}
- return result;
+
+ return handle_result(::magic_descriptor(m_cookie, file_descriptor));
}
- auto magic::process(int file_descriptor) -> std::expected<std::string, std::string>
+ auto magic::handle_result(char const * result) -> std::expected<std::string, std::error_code>
{
- auto result = ::magic_descriptor(m_cookie, file_descriptor);
+ auto errno_copy = errno;
+
if (!result)
{
- return std::unexpected{std::string{::magic_error(m_cookie)}};
+ auto magic_errno = ::magic_errno(m_cookie);
+ if (!magic_errno && !errno)
+ {
+ return std::unexpected{std::make_error_code(std::errc::invalid_argument)};
+ }
}
- return result;
+
+ return std::string{result};
}
auto swap(magic & lhs, magic & rhs) noexcept -> void
diff --git a/cabinet/magic.hpp b/cabinet/magic.hpp
index 96f4b08..9e078de 100644
--- a/cabinet/magic.hpp
+++ b/cabinet/magic.hpp
@@ -54,10 +54,12 @@ namespace cab
auto operator=(magic const &) -> magic & = delete;
auto operator=(magic && other) noexcept -> magic &;
- auto process(std::filesystem::path path) -> std::expected<std::string, std::string>;
- auto process(int file_descriptor) -> std::expected<std::string, std::string>;
+ auto process(std::filesystem::path path) -> std::expected<std::string, std::error_code>;
+ auto process(int file_descriptor) -> std::expected<std::string, std::error_code>;
private:
+ auto handle_result(char const * result) -> std::expected<std::string, std::error_code>;
+
explicit magic(::magic_t cookie) noexcept;
::magic_t m_cookie{};
diff --git a/cabinet/main.cpp b/cabinet/main.cpp
index db2d43b..ff35d34 100644
--- a/cabinet/main.cpp
+++ b/cabinet/main.cpp
@@ -27,7 +27,7 @@ auto main(int argc, char ** argv) -> int
auto mime_type = magic->process(fd);
if (!mime_type)
{
- std::println(std::cerr, "Failed to determine file type: {}", mime_type.error());
+ std::println(std::cerr, "Failed to determine file type: {}", mime_type.error().message());
return EXIT_FAILURE;
}
std::println("{}: {}", argv[1], mime_type.value());