Skip to content

Commit

Permalink
Don't remove type alongside heterogeneous enumerations (#213)
Browse files Browse the repository at this point in the history
Signed-off-by: Juan Cruz Viotti <[email protected]>
  • Loading branch information
jviotti authored Sep 10, 2024
1 parent 2594835 commit a7fd9aa
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/linter/antipattern/enum_with_type.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,34 @@ class EnumWithType final : public Rule {
"http://json-schema.org/draft-02/hyper-schema#",
"http://json-schema.org/draft-01/hyper-schema#"}) &&
schema.is_object() && schema.defines("type") &&
schema.defines("enum");
schema.defines("enum") &&

// Guard against cases where not all of the enumeration members
// match the desired type, in which case the type is adding
// an extra constraint and cannot be safely removed
schema.at("type").is_string() && schema.at("enum").is_array() &&
std::all_of(schema.at("enum").as_array().cbegin(),
schema.at("enum").as_array().cend(),
[&schema](const auto &item) {
const auto &type{schema.at("type").to_string()};
if (type == "object") {
return item.is_object();
} else if (type == "array") {
return item.is_array();
} else if (type == "string") {
return item.is_string();
} else if (type == "boolean") {
return item.is_boolean();
} else if (type == "null") {
return item.is_null();
} else if (type == "number") {
return item.is_number();
} else if (type == "integer") {
return item.is_integer();
} else {
return false;
}
});
}

auto transform(Transformer &transformer) const -> void override {
Expand Down
20 changes: 20 additions & 0 deletions test/linter/2020_12_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,26 @@ TEST(Lint_2020_12, enum_with_type_1) {
EXPECT_EQ(document, expected);
}

TEST(Lint_2020_12, enum_with_type_2) {
sourcemeta::jsontoolkit::JSON document =
sourcemeta::jsontoolkit::parse(R"JSON({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "string",
"enum": [ "foo", 1 ]
})JSON");

LINT_AND_FIX(document);

const sourcemeta::jsontoolkit::JSON expected =
sourcemeta::jsontoolkit::parse(R"JSON({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "string",
"enum": [ "foo", 1 ]
})JSON");

EXPECT_EQ(document, expected);
}

TEST(Lint_2020_12, single_type_array_1) {
sourcemeta::jsontoolkit::JSON document =
sourcemeta::jsontoolkit::parse(R"JSON({
Expand Down

0 comments on commit a7fd9aa

Please sign in to comment.