Skip to content

extract_name

NameExtractor

Extract Context Value, from a User's Config (YAML) file.

Source code in src/cookiecutter_python/backend/hosting_services/extract_name.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@attr.s(auto_attribs=True, slots=True, frozen=True)
class NameExtractor:
    """Extract Context Value, from a User's Config (YAML) file."""

    name_extractor: Callable[[Mapping], str]

    def __call__(self, config_file: str) -> str:
        # Delegate to Cookiecutter YAML parsing of User Config
        # config_data: GeneratorYamlData = get_user_config(
        config_data = get_user_config(
            config_file=config_file,
            # MUST be False, otherwise Cookiecutter does not do YAML parsing
            default_config=False,
        )
        context_data = config_data['default_context']
        try:
            return self.name_extractor(context_data)
        except KeyError as error:
            raise ContextVariableDoesNotExist(
                "{msg}: {data}".format(
                    msg="Attempted to retrieve non-existant variable",
                    data=json.dumps(
                        {
                            'variable_name': str(self.name_extractor),
                            'available_variables': '[{keys}]'.format(
                                keys=', '.join(
                                    tuple(sorted([str(x) for x in context_data.keys()]))
                                ),
                            ),
                        },
                        indent=4,
                        sort_keys=True,
                    ),
                ),
            ) from error

    @staticmethod
    def create(hosting_service_info):
        return NameExtractor(BaseValueExtractor(hosting_service_info.variable_name))