How to use the nitpick.formats.TOMLFormat function in nitpick

To help you get started, we’ve selected a few nitpick examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github andreoliwa / nitpick / tests / helpers.py View on Github external
def assert_merged_style(self, toml_string: str):
        """Assert the contents of the merged style file."""
        expected = TOMLFormat(path=self.cache_dir / MERGED_STYLE_TOML)
        actual = TOMLFormat(string=dedent(toml_string))
        compare(expected.as_data, actual.as_data)
github andreoliwa / nitpick / tests / helpers.py View on Github external
def assert_merged_style(self, toml_string: str):
        """Assert the contents of the merged style file."""
        expected = TOMLFormat(path=self.cache_dir / MERGED_STYLE_TOML)
        actual = TOMLFormat(string=dedent(toml_string))
        compare(expected.as_data, actual.as_data)
github andreoliwa / nitpick / src / nitpick / style.py View on Github external
def file_field_pair(file_name: str, base_file_class: Type[NitpickPlugin]) -> Dict[str, fields.Field]:
        """Return a schema field with info from a config file class."""
        valid_toml_key = TOMLFormat.group_name_for(file_name)
        unique_file_name_with_underscore = slugify(file_name, separator="_")

        kwargs = {"data_key": valid_toml_key}
        if base_file_class.validation_schema:
            field = fields.Nested(base_file_class.validation_schema, **kwargs)
        else:
            # For default files (pyproject.toml, setup.cfg...), there is no strict schema;
            # it can be anything they allow.
            # It's out of Nitpick's scope to validate those files.
            field = fields.Dict(fields.String, **kwargs)
        return {unique_file_name_with_underscore: field}
github andreoliwa / nitpick / src / nitpick / plugins / pre_commit.py View on Github external
def handle_config_file(  # pylint: disable=unused-argument
    config: JsonDict, file_name: str, tags: Set[str]
) -> Optional["NitpickPlugin"]:
    """Handle pre-commit config file."""
    return PreCommitPlugin(config) if file_name == TOMLFormat.group_name_for(PreCommitPlugin.file_name) else None
github andreoliwa / nitpick / src / nitpick / style.py View on Github external
def include_multiple_styles(self, chosen_styles: StrOrList) -> None:
        """Include a list of styles (or just one) into this style tree."""
        style_uris = [chosen_styles] if isinstance(chosen_styles, str) else chosen_styles  # type: List[str]
        for style_uri in style_uris:
            style_path = self.get_style_path(style_uri)  # type: Optional[Path]
            if not style_path:
                continue

            toml = TOMLFormat(path=style_path)
            try:
                toml_dict = toml.as_data
            except TomlDecodeError as err:
                NitpickApp.current().add_style_error(style_path.name, pretty_exception(err, "Invalid TOML"))
                # If the TOML itself could not be parsed, we can't go on
                return

            try:
                display_name = str(style_path.relative_to(NitpickApp.current().root_dir))
            except ValueError:
                display_name = style_uri
            self.validate_style(display_name, toml_dict)
            self._all_styles.add(toml_dict)

            sub_styles = search_dict(NITPICK_STYLES_INCLUDE_JMEX, toml_dict, [])  # type: StrOrList
            if sub_styles:
github andreoliwa / nitpick / src / nitpick / plugins / base.py View on Github external
def check_exists(self) -> YieldFlake8Error:
        """Check if the file should exist."""
        config_data_exists = bool(self.file_dict or self.nitpick_file_dict)
        should_exist = NitpickApp.current().config.nitpick_files_section.get(
            TOMLFormat.group_name_for(self.file_name), True
        )  # type: bool
        file_exists = self.file_path.exists()

        if config_data_exists and not file_exists:
            suggestion = self.suggest_initial_contents()
            phrases = [" was not found"]
            message = NitpickApp.current().config.nitpick_files_section.get(self.file_name)
            if message and isinstance(message, str):
                phrases.append(message)
            if suggestion:
                phrases.append("Create it with this content:")
            yield self.flake8_error(1, ". ".join(phrases), suggestion)
        elif not should_exist and file_exists:
            # Only display this message if the style is valid.
            if not NitpickApp.current().style_errors:
                yield self.flake8_error(2, " should be deleted")
github andreoliwa / nitpick / src / nitpick / style.py View on Github external
def merge_toml_dict(self) -> JsonDict:
        """Merge all included styles into a TOML (actually JSON) dictionary."""
        app = NitpickApp.current()
        if not app.cache_dir:
            return {}
        merged_dict = self._all_styles.merge()
        merged_style_path = app.cache_dir / MERGED_STYLE_TOML  # type: Path
        toml = TOMLFormat(data=merged_dict)

        attempt = 1
        while attempt < 5:
            try:
                app.cache_dir.mkdir(parents=True, exist_ok=True)
                merged_style_path.write_text(toml.reformatted)
                break
            except OSError:
                attempt += 1

        return merged_dict
github andreoliwa / nitpick / src / nitpick / config.py View on Github external
def validate_pyproject_tool_nitpick(self) -> bool:
        """Validate the ``pyroject.toml``'s ``[tool.nitpick]`` section against a Marshmallow schema."""
        pyproject_path = NitpickApp.current().root_dir / PyProjectTomlPlugin.file_name  # type: Path
        if pyproject_path.exists():
            self.pyproject_toml = TOMLFormat(path=pyproject_path)
            self.tool_nitpick_dict = search_dict(TOOL_NITPICK_JMEX, self.pyproject_toml.as_data, {})
            pyproject_errors = ToolNitpickSectionSchema().validate(self.tool_nitpick_dict)
            if pyproject_errors:
                NitpickApp.current().add_style_error(
                    PyProjectTomlPlugin.file_name,
                    "Invalid data in [{}]:".format(TOOL_NITPICK),
                    flatten_marshmallow_errors(pyproject_errors),
                )
                return False
        return True