LibGUI: Make CommonLocationsProvider::load_from_json() failable

... and additionally port it to Core::Stream. :^)
This commit is contained in:
Karol Kosek 2023-01-08 22:25:28 +01:00 committed by Jelle Raaijmakers
parent 493658423a
commit 41691a7fcb
Notes: sideshowbarker 2024-07-17 07:06:47 +09:00
2 changed files with 16 additions and 20 deletions

View File

@ -10,6 +10,7 @@
#include <AK/Vector.h>
#include <LibCore/File.h>
#include <LibCore/StandardPaths.h>
#include <LibCore/Stream.h>
#include <LibGUI/CommonLocationsProvider.h>
#include <unistd.h>
@ -25,8 +26,11 @@ static void initialize_if_needed()
auto user_config = DeprecatedString::formatted("{}/CommonLocations.json", Core::StandardPaths::config_directory());
if (Core::File::exists(user_config)) {
CommonLocationsProvider::load_from_json(user_config);
return;
auto maybe_error = CommonLocationsProvider::load_from_json(user_config);
if (!maybe_error.is_error())
return;
dbgln("Unable to read Common Locations file: {}", maybe_error.error());
dbgln("Using the default set instead.");
}
// Fallback : If the user doesn't have custom locations, use some default ones.
@ -36,23 +40,14 @@ static void initialize_if_needed()
s_initialized = true;
}
void CommonLocationsProvider::load_from_json(DeprecatedString const& json_path)
ErrorOr<void> CommonLocationsProvider::load_from_json(StringView json_path)
{
auto file = Core::File::construct(json_path);
if (!file->open(Core::OpenMode::ReadOnly)) {
dbgln("Unable to open {}", file->filename());
return;
}
auto json = JsonValue::from_string(file->read_all());
if (json.is_error()) {
dbgln("Common locations file {} is not a valid JSON file.", file->filename());
return;
}
if (!json.value().is_array()) {
dbgln("Common locations file {} should contain a JSON array.", file->filename());
return;
}
auto file = TRY(Core::Stream::File::open(json_path, Core::Stream::OpenMode::Read));
auto json = JsonValue::from_string(TRY(file->read_until_eof()));
if (json.is_error())
return Error::from_string_literal("File is not a valid JSON");
if (!json.value().is_array())
return Error::from_string_literal("File must contain a JSON array");
s_common_locations.clear();
auto const& contents = json.value().as_array();
@ -63,10 +58,11 @@ void CommonLocationsProvider::load_from_json(DeprecatedString const& json_path)
auto entry = entry_value.as_object();
auto name = entry.get("name"sv).to_deprecated_string();
auto path = entry.get("path"sv).to_deprecated_string();
s_common_locations.append({ name, path });
TRY(s_common_locations.try_append({ name, path }));
}
s_initialized = true;
return {};
}
Vector<CommonLocationsProvider::CommonLocation> const& CommonLocationsProvider::common_locations()

View File

@ -20,7 +20,7 @@ public:
DeprecatedString path;
};
static void load_from_json(DeprecatedString const& json_path);
static ErrorOr<void> load_from_json(StringView json_path);
static Vector<CommonLocation> const& common_locations();
};