phml.utils.misc.component

 1# pylint: disable=missing-module-docstring
 2from pathlib import Path
 3
 4from phml.nodes import AST, Element
 5
 6__all__ = ["tag_from_file", "filename_from_path", "parse_component"]
 7
 8
 9def tag_from_file(filename: str) -> str:
10    """Generates a tag name some-tag-name from a filename.
11    Assumes filenames of:
12    * snakecase - some_file_name
13    * camel case - someFileName
14    * pascal case - SomeFileName
15    """
16    from re import finditer  # pylint: disable=import-outside-toplevel
17
18    tokens = []
19    for token in finditer(r"(\b|[A-Z]|_)([a-z]+)", filename):
20        first, rest = token.groups()
21        if first.isupper():
22            rest = first + rest
23        tokens.append(rest.lower())
24
25    return "-".join(tokens)
26
27
28def filename_from_path(file: Path) -> str:
29    """Get the filename without the suffix from a pathlib.Path."""
30
31    if file.is_file():
32        return file.name.replace(file.suffix, "")
33
34    raise TypeError(f"Expected {type(Path)} not {type(file)}")
35
36
37def parse_component(ast: AST) -> dict[str, Element]:
38    """Helper function to parse the components elements."""
39    from phml.utils import test, visit_children  # pylint: disable=import-outside-toplevel
40
41    result = {"python": [], "script": [], "style": [], "component": None}
42    for node in visit_children(ast.tree):
43        if test(node, ["element", {"tag": "python"}]):
44            result["python"].append(node)
45        elif test(node, ["element", {"tag": "script"}]):
46            result["script"].append(node)
47        elif test(node, ["element", {"tag": "style"}]):
48            result["style"].append(node)
49        elif test(node, "element"):
50            if result["component"] is None:
51                result["component"] = node
52            else:
53                raise Exception(
54                    """\
55Components may only have one wrapping element. All other element in the root must be either a \
56script, style, or python tag.\
57"""
58                )
59
60    if result["component"] is None:
61        raise Exception("Must have at least one element in a component.")
62
63    return result
def tag_from_file(filename: str) -> str:
10def tag_from_file(filename: str) -> str:
11    """Generates a tag name some-tag-name from a filename.
12    Assumes filenames of:
13    * snakecase - some_file_name
14    * camel case - someFileName
15    * pascal case - SomeFileName
16    """
17    from re import finditer  # pylint: disable=import-outside-toplevel
18
19    tokens = []
20    for token in finditer(r"(\b|[A-Z]|_)([a-z]+)", filename):
21        first, rest = token.groups()
22        if first.isupper():
23            rest = first + rest
24        tokens.append(rest.lower())
25
26    return "-".join(tokens)

Generates a tag name some-tag-name from a filename. Assumes filenames of:

  • snakecase - some_file_name
  • camel case - someFileName
  • pascal case - SomeFileName
def filename_from_path(file: pathlib.Path) -> str:
29def filename_from_path(file: Path) -> str:
30    """Get the filename without the suffix from a pathlib.Path."""
31
32    if file.is_file():
33        return file.name.replace(file.suffix, "")
34
35    raise TypeError(f"Expected {type(Path)} not {type(file)}")

Get the filename without the suffix from a pathlib.Path.

def parse_component(ast: phml.nodes.AST.AST) -> dict[str, phml.nodes.element.Element]:
38def parse_component(ast: AST) -> dict[str, Element]:
39    """Helper function to parse the components elements."""
40    from phml.utils import test, visit_children  # pylint: disable=import-outside-toplevel
41
42    result = {"python": [], "script": [], "style": [], "component": None}
43    for node in visit_children(ast.tree):
44        if test(node, ["element", {"tag": "python"}]):
45            result["python"].append(node)
46        elif test(node, ["element", {"tag": "script"}]):
47            result["script"].append(node)
48        elif test(node, ["element", {"tag": "style"}]):
49            result["style"].append(node)
50        elif test(node, "element"):
51            if result["component"] is None:
52                result["component"] = node
53            else:
54                raise Exception(
55                    """\
56Components may only have one wrapping element. All other element in the root must be either a \
57script, style, or python tag.\
58"""
59                )
60
61    if result["component"] is None:
62        raise Exception("Must have at least one element in a component.")
63
64    return result

Helper function to parse the components elements.