Skip to content

Commit

Permalink
refacto(header): transforme la liste de clés obligatoires en enum (#225)
Browse files Browse the repository at this point in the history
- vu que je fais joujou avec les enums en ce moment dans d'autres
projets (DicoGIS), ça m'a donné des idées
- j'en ai profité pour ajouter la docstring sur la fonction impactée

Pour info, je n'ai pas retiré "license" puisque c'est fait dans #215
  • Loading branch information
Guts authored Jul 2, 2024
2 parents cd0c939 + 892deba commit b2ef10b
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 23 deletions.
58 changes: 58 additions & 0 deletions geotribu_cli/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
# standard library
import logging
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Literal

Expand All @@ -21,6 +22,59 @@
# ################################


class ExtendedEnum(Enum):
"""Custom Enum with extended methods."""

@classmethod
def has_key(cls, name: str) -> bool:
"""Check if a certain key is present in enum.
Source: https://stackoverflow.com/a/62065380/2556577
Args:
name (str): key to check.
Returns:
bool: True if the key exists.
"""
return name in cls.__members__

@classmethod
def has_value(cls, value: str) -> bool:
"""Check if a certain value is present in enum.
Source: https://stackoverflow.com/a/43634746/2556577
Args:
value (str): value to check
Returns:
bool: True is the value exists.
"""
return value in cls._value2member_map_

@classmethod
def values_set(cls) -> set:
"""Return a set of enum values.
Returns:
set of enum's unique values
"""
return {item.value for item in cls}


class YamlHeaderMandatoryKeys(ExtendedEnum):
"""Clés obligatoires dans l'en-tête d'un contenu Geotribu."""

AUTHORS = "authors"
CATEGORIES = "categories"
DATE = "date"
DESCRIPTION = "description"
LICENSE = "license"
TAGS = "tags"
TITLE = "title"


@dataclass
class GeotribuDefaults:
"""Defaults settings for Geotribu."""
Expand Down Expand Up @@ -113,3 +167,7 @@ def site_git_source_base_url(
if __name__ == "__main__":
defaults = GeotribuDefaults()
print(defaults.cdn_search_index_full_url)
print(YamlHeaderMandatoryKeys.TITLE.value)
print("title" in YamlHeaderMandatoryKeys.__members__)
print("title" in YamlHeaderMandatoryKeys._value2member_map_)
print({item.value for item in YamlHeaderMandatoryKeys})
35 changes: 15 additions & 20 deletions geotribu_cli/content/header_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import frontmatter

from geotribu_cli.constants import GeotribuDefaults
from geotribu_cli.constants import GeotribuDefaults, YamlHeaderMandatoryKeys
from geotribu_cli.json.json_client import JsonFeedClient
from geotribu_cli.utils.check_image_size import get_image_dimensions_by_url
from geotribu_cli.utils.check_path import check_path
Expand All @@ -14,16 +14,6 @@
logger = logging.getLogger(__name__)
defaults_settings = GeotribuDefaults()

MANDATORY_KEYS = [
"title",
"authors",
"categories",
"date",
"description",
"license",
"tags",
]

# ############################################################################
# ########## CLI #################
# ################################
Expand Down Expand Up @@ -137,13 +127,20 @@ def check_tags_order(tags: list[str]) -> bool:
return True


def check_mandatory_keys(
keys: list[str], mandatory: list[str] = MANDATORY_KEYS
) -> tuple[bool, set[str]]:
def check_missing_mandatory_keys(keys: list[str]) -> tuple[bool, set[str]]:
"""Liste les clés de l'en-tête qui sont manquantes par rapport à celles requises.
Args:
keys: clés de l'en-tête à comparer
Returns:
un tuple à 2 valeurs composé d'un booléen indiquant s'il manque une clé
obligatoire et la liste des clés manquantes
"""
missing = set()
for mk in mandatory:
if mk not in keys:
missing.add(mk)
for mandatory_key in YamlHeaderMandatoryKeys.values_set():
if mandatory_key not in keys:
missing.add(mandatory_key)
return len(missing) == 0, missing


Expand Down Expand Up @@ -227,9 +224,7 @@ def run(args: argparse.Namespace) -> None:
logger.info("Ordre alphabétique des tags ok")

# check that mandatory keys are present
all_present, missing = check_mandatory_keys(
yaml_meta.keys(), MANDATORY_KEYS
)
all_present, missing = check_missing_mandatory_keys(yaml_meta.keys())
if not all_present:
msg = f"Les clés suivantes ne sont pas présentes dans l'entête markdown : {','.join(missing)}"
logger.error(msg)
Expand Down
9 changes: 6 additions & 3 deletions tests/test_yaml_header_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
from geotribu_cli.content.header_check import (
check_author_md,
check_existing_tags,
check_mandatory_keys,
check_missing_mandatory_keys,
check_tags_order,
)

# -- GLOBALS
TEAM_FOLDER = Path("tests/fixtures/team")


Expand Down Expand Up @@ -56,12 +57,14 @@ def test_future_tags_order(self):
self.assertFalse(check_tags_order(self.future_yaml_meta["tags"]))

def test_past_mandatory_keys(self):
all_present, missing = check_mandatory_keys(self.past_yaml_meta.keys())
all_present, missing = check_missing_mandatory_keys(self.past_yaml_meta.keys())
self.assertTrue(all_present)
self.assertEqual(len(missing), 0)

def test_future_mandatory_keys(self):
all_present, missing = check_mandatory_keys(self.future_yaml_meta.keys())
all_present, missing = check_missing_mandatory_keys(
self.future_yaml_meta.keys()
)
self.assertFalse(all_present)
self.assertEqual(len(missing), 2)
self.assertIn("license", missing)
Expand Down

0 comments on commit b2ef10b

Please sign in to comment.