Esempio n. 1
0
    def command(self) -> Optional[plug.Result]:
        """A callback function that runs the sanitization protocol on a given
        file.

        Returns:
            Result if the syntax is invalid, otherwise nothing.
        """

        infile_encoding = _fileutils.guess_encoding(self.infile)
        infile_content = self.infile.read_text(
            encoding=infile_encoding).split("\n")

        errors = _syntax.check_syntax(infile_content)
        if errors:
            file_errors = [_format.FileWithErrors(self.infile.name, errors)]
            msg = _format.format_error_string(file_errors)

            return plug.Result(
                name="sanitize-file",
                msg=msg,
                status=plug.Status.ERROR,
            )

        result = _sanitize.sanitize_text(infile_content, strip=self.strip)
        if result:
            self.outfile.write_text(result, encoding=infile_encoding)

        return plug.Result(
            name="sanitize-file",
            msg="Successfully sanitized file",
            status=plug.Status.SUCCESS,
        )
Esempio n. 2
0
def sanitize_files(
    basedir: pathlib.Path, file_relpaths: List[_fileutils.RelativePath]
) -> List[_format.FileWithErrors]:
    """Checks the syntax of the provided files and reports any found errors.
    If any errors are found, report errors and exits. If there are no errors,
    then all files are sanitized."""
    files_with_errors = []

    for relpath in file_relpaths:
        text = relpath.read_text_relative_to(basedir)
        errors = _syntax.check_syntax(text.split("\n"))
        if errors:
            files_with_errors.append(_format.FileWithErrors(relpath, errors))

    if files_with_errors:
        return files_with_errors

    for relpath in file_relpaths:
        content = relpath.read_text_relative_to(basedir).split("\n")
        sanitized_text = _sanitize.sanitize_text(content)
        if sanitized_text is None:
            (basedir / str(relpath)).unlink()
            LOGGER.info(f"Shredded file {relpath}")
        else:
            relpath.write_text_relative_to(data=sanitized_text,
                                           basedir=basedir)
            LOGGER.info(f"Sanitized {relpath}")

    return []