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 []
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, )
def test_sanitize_invalid(text: str): assert _syntax.check_syntax(text)
def test_check_syntax_with_empty_string(): """Check_syntax is a public function, therefore we have to check what happens if we give it an empty string. If it returns a anything, we know that it has the proper behavior, since it should fail on an empty file. """ assert _syntax.check_syntax([""])