| #!/usr/bin/env python3 | |
| # Copyright 2025 The ChromiumOS Authors | |
| # Use of this source code is governed by a BSD-style license that can be | |
| # found in the LICENSE file. | |
| """Format our source files.""" | |
| import logging | |
| import os | |
| from pathlib import Path | |
| import sys | |
| from typing import Optional | |
| import libdot | |
| def process_html_files( | |
| paths: list[Path], fix: bool, gerrit_comments_file: bool | |
| ) -> bool: | |
| """Process HTML files.""" | |
| del gerrit_comments_file | |
| cmd = ["prettier", "-w" if fix else "-c"] + paths | |
| result = libdot.node.run(cmd, check=False) | |
| return result.returncode == 0 | |
| def process_text_files( | |
| paths: list[Path], fix: bool, gerrit_comments_file: bool | |
| ) -> bool: | |
| """Process plain text files.""" | |
| del gerrit_comments_file | |
| ret = True | |
| for path in paths: | |
| with open(path, encoding="utf-8") as fp: | |
| data = fp.read() | |
| # NB: Keep logic in sync with the lint script. | |
| new_data = data.lstrip("\n").rstrip("\n").replace("\r", "") | |
| if new_data: | |
| new_data += "\n" | |
| if data != new_data: | |
| if fix: | |
| with open(path, "w", encoding="utf-8") as fp: | |
| fp.write(new_data) | |
| else: | |
| logging.error("%s: whitespace incorrect", path) | |
| ret = False | |
| return ret | |
| def get_parser() -> libdot.ArgumentParser: | |
| """Get a command line parser.""" | |
| parser = libdot.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "--version", action="store_true", help="Show tool versions." | |
| ) | |
| parser.add_argument( | |
| "--fix", | |
| action="store_true", | |
| help="Run tools with --fix setting if possible.", | |
| ) | |
| parser.add_argument( | |
| "--gerrit-comments-file", | |
| help="Save errors for posting files to Gerrit.", | |
| ) | |
| group = parser.add_argument_group( | |
| "File selection/filtering", | |
| description="All files are checked by default", | |
| ) | |
| group.add_argument("--cpp", action="store_true", help="Check C/C++ files.") | |
| group.add_argument( | |
| "--html", action="store_true", help="Check HTML/CSS files." | |
| ) | |
| group.add_argument("--py", action="store_true", help="Check Python files.") | |
| group.add_argument("--txt", action="store_true", help="Lint text files.") | |
| parser.add_argument("paths", nargs="*", help="Paths to check.") | |
| return parser | |
| def main( | |
| argv: list[str], | |
| get_default_paths=libdot.lint.get_known_sources, | |
| basedir: Optional[Path] = None, | |
| ) -> int: | |
| """The main func! | |
| Args: | |
| argv: The command line to process. | |
| get_default_paths: Function to find files to check. | |
| basedir: The base source tree to search for default set of files. | |
| """ | |
| parser = get_parser() | |
| opts = parser.parse_args(argv) | |
| libdot.node_and_npm_setup() | |
| if opts.version: | |
| for func in (libdot.black.run,): | |
| func(["--version"]) | |
| return 0 | |
| if not opts.paths: | |
| opts.paths = [str(x) for x in get_default_paths(basedir)] | |
| if not opts.paths: | |
| print("No files to check.") | |
| return 0 | |
| check_groups = {"cpp", "html", "py", "txt"} | |
| check_all = all(not getattr(opts, x) for x in check_groups) | |
| for group in check_groups: | |
| setattr(opts, group, check_all or getattr(opts, group)) | |
| tocheck_paths = set(opts.paths) | |
| kwargs = { | |
| "fix": opts.fix, | |
| "gerrit_comments_file": opts.gerrit_comments_file, | |
| } | |
| checks = [] | |
| html_files = [ | |
| x | |
| for x in opts.paths | |
| if x.endswith(".css") or x.endswith(".html") or x.endswith(".html.in") | |
| ] | |
| cpp_files = libdot.cpplint.filter_known_files(opts.paths) | |
| tocheck_paths -= set(cpp_files) | |
| if cpp_files and opts.cpp: | |
| cpp_kwargs = {"paths": cpp_files, **kwargs} | |
| checks += [libdot.clang_format.perform(**cpp_kwargs)] | |
| tocheck_paths -= set(html_files) | |
| if html_files and opts.html: | |
| checks += [process_html_files(html_files, **kwargs)] | |
| py_files = libdot.pylint.filter_known_files(opts.paths) | |
| tocheck_paths -= set(py_files) | |
| if py_files and opts.py: | |
| py_kwargs = {"paths": py_files, **kwargs} | |
| checks += [libdot.black.perform(**py_kwargs)] | |
| TEXT_FILENAMES = { | |
| ".clang-format", | |
| ".gitignore", | |
| ".markdownlintrc", | |
| ".npmrc", | |
| ".prettierignore", | |
| ".pylintrc", | |
| "DIR_METADATA", | |
| "Dockerfile", | |
| "eslint.config.js", | |
| "LICENSE", | |
| "Makefile", | |
| "METADATA", | |
| "OWNERS", | |
| } | |
| TEXT_EXTENSIONS = { | |
| ".cfg", | |
| ".concat", | |
| ".css", | |
| ".el", | |
| ".md", | |
| ".sh", | |
| ".svg", | |
| ".toml", | |
| ".txt", | |
| ".vim", | |
| ".xml", | |
| ".yaml", | |
| } | |
| text_files = [ | |
| x | |
| for x in opts.paths | |
| if ( | |
| os.path.basename(x) in TEXT_FILENAMES | |
| or os.path.splitext(x)[1] in TEXT_EXTENSIONS | |
| ) | |
| ] | |
| tocheck_paths -= set(text_files) | |
| if text_files and opts.txt: | |
| checks += [process_text_files(text_files, **kwargs)] | |
| if tocheck_paths: | |
| logging.warning( | |
| "Formatting skipped:\n%s", " ".join(sorted(tocheck_paths)) | |
| ) | |
| return 0 if all(checks) else 1 | |
| if __name__ == "__main__": | |
| sys.exit( | |
| main( | |
| sys.argv[1:], | |
| basedir=libdot.DIR, | |
| ) | |
| ) |