Skip to content

Commit

Permalink
Merge pull request #10 from moneymeets/feature/refactor-identifiers-g…
Browse files Browse the repository at this point in the history
…enerators

Feature/refactor identifiers generators
  • Loading branch information
catcombo authored Oct 30, 2024
2 parents fa44013 + 6005ac3 commit ad9a7e3
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 8 deletions.
14 changes: 6 additions & 8 deletions spec2sdk/generators/identifiers.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import re
from keyword import iskeyword
from typing import Final, Pattern

from humps import decamelize, pascalize

INVALID_CHARACTERS_PATTERN: Final[Pattern] = re.compile(r"[^0-9a-z]+|^[^a-z]+", flags=re.IGNORECASE)


def make_identifier(name: str) -> str:
"""
Makes valid Python identifier from the string.
Makes valid Python identifier from the string by removing invalid leading characters
and replacing invalid characters with underscore.
"""
# Remove invalid characters
name = re.sub(r"[^0-9a-zA-Z_]", "_", name)

# Remove leading characters until we find a letter
name = re.sub(r"^[^a-zA-Z]+", "", name)

# Replace consecutive duplicates of the underscore
name = re.sub(r"_+", "_", name)
name = "_".join(name_part for name_part in INVALID_CHARACTERS_PATTERN.split(name) if name_part)

# Add underscore to the name if it's a valid Python keyword
if iskeyword(name):
Expand Down
Empty file added tests/generators/__init__.py
Empty file.
25 changes: 25 additions & 0 deletions tests/generators/test_identifiers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from spec2sdk.generators.identifiers import make_class_name, make_constant_name, make_identifier, make_variable_name


def test_remove_invalid_leading_characters():
assert make_identifier("12+34-_56Variable78Name90") == "Variable78Name90"


def test_replace_invalid_characters():
assert make_identifier("Variable12%#&34(@!56Name78*-,") == "Variable12_34_56Name78"


def test_python_keywords():
assert make_identifier("def") == "def_"


def test_make_class_name():
assert make_class_name("issue:comment") == "IssueComment"


def test_make_constant_name():
assert make_constant_name("family_status") == "FAMILY_STATUS"


def test_make_variable_name():
assert make_variable_name("UserID") == "user_id"

0 comments on commit ad9a7e3

Please sign in to comment.