| # Copyright (C) 2026 The Android Open Source Project | |
| # | |
| # Licensed under the Apache License, Version 2.0 (the "License"); | |
| # you may not use this file except in compliance with the License. | |
| # You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| # See the License for the specific language governing permissions and | |
| # limitations under the License. | |
| import os | |
| import pathlib | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| from typing import Any | |
| import bp | |
| from .constants import POD_DIRECTORIES, LINT_DISABLE_PREFIX | |
| from .lint_collector import LintCollector | |
| from .lint_rules import ( | |
| AlphabetizeListRule, ApiNameRule, BpOrderRule, ModuleTypeRule, ApiManifestNameRule, | |
| ApiNoImplDependenciesRule, ImplNameRule, | |
| ImplManifestNameRule, ImplApiDependencyRule, ImplOtherImplDependencyRule, | |
| DaggerNameRule, AllowedPropertiesRule, PropertyOrderRule, TestNameRule | |
| ) | |
| def initialize_cmd(subparsers): | |
| lint_parser = subparsers.add_parser( | |
| "lint", | |
| help="Validate pods (TODO: unimplemented)" | |
| ) | |
| lint_parser.set_defaults(func=lint) | |
| lint_parser.add_argument( | |
| "-a", "--all", | |
| action="store_true", | |
| help="Whether to parse all pods. Defaults to only pods with pending git changes." | |
| ) | |
| lint_parser.add_argument( | |
| "-f", "--fix", | |
| action="store_true", | |
| help="Whether to automatically apply any available fixes to lint errors." | |
| ) | |
| lint_parser.add_argument( | |
| "--no-fix", | |
| action="store_true", | |
| help="Do not prompt to fix any errors found." | |
| ) | |
| lint_parser.add_argument( | |
| "-c", "--commit", "--sha", | |
| dest="commit", | |
| help="Git commit ID (SHA hash) to lint." | |
| ) | |
| lint_parser.add_argument( | |
| "bps", | |
| nargs="*", | |
| help="Arbitrary Android.bp files to validate." | |
| ) | |
| def _resolve_pod_dir(root_path, pod_dir): | |
| candidate = (pathlib.Path(root_path) / pod_dir).resolve() | |
| if candidate.exists(): | |
| return candidate | |
| parts = pod_dir.parts | |
| for i in range(1, len(parts)): | |
| candidate = (pathlib.Path(root_path) / pathlib.Path(*parts[i:])).resolve() | |
| if candidate.exists(): | |
| return candidate | |
| return (pathlib.Path(root_path) / pod_dir).resolve() | |
| def lint(args, logger): | |
| bps = [] | |
| root_paths = [pathlib.Path(os.path.abspath(p)).resolve() for p in args.path] | |
| # If an explicit list of bps is passed in... | |
| if args.bps: | |
| for f in args.bps: | |
| if not f.endswith(".bp"): | |
| logger.debug(f"Argument '{f}' does not end in '.bp'") | |
| continue | |
| # Find the bp relative to any paths that were set. | |
| bps.extend(_file_relative_to_paths(f, root_paths, logger)) | |
| elif args.commit: | |
| search_paths = list(root_paths) if root_paths else [] | |
| for pod_dir in POD_DIRECTORIES.values(): | |
| for root in root_paths: | |
| search_paths.append(_resolve_pod_dir(root, pod_dir)) | |
| bps = _get_commit_bp_files(args.commit, search_paths, root_paths) | |
| # else try to detect changed bp files | |
| elif not args.all: | |
| cwd = pathlib.Path.cwd().resolve() | |
| try: | |
| # Test if we're in a git repo, and if we are, lint any changed bp files | |
| subprocess.run( | |
| ["git", "rev-parse", "--is-inside-work-tree"], | |
| cwd=cwd, | |
| capture_output=True, | |
| check=True | |
| ) | |
| bps = _get_changed_bp_files(cwd, root_paths) | |
| except subprocess.CalledProcessError: | |
| # If we're not in a git repo then look for changes in all the pod directories we know of | |
| for pod_dir in POD_DIRECTORIES.values(): | |
| for root in root_paths: | |
| pod_abs = _resolve_pod_dir(root, pod_dir) | |
| bps.extend(_get_changed_bp_files(pod_abs, root_paths)) | |
| if not bps and args.all: | |
| dirs = [] | |
| for pod_dir in POD_DIRECTORIES.values(): | |
| for root in root_paths: | |
| dirs.append(_resolve_pod_dir(root, pod_dir)) | |
| abs_bps = bp.locate.find_bp_files(*dirs) | |
| for abs_bp in abs_bps: | |
| for root in root_paths: | |
| try: | |
| rel = abs_bp.relative_to(root) | |
| if rel not in bps: | |
| bps.append(rel) | |
| break | |
| except ValueError: | |
| continue | |
| if not bps: | |
| logger.info("No Android.bp to lint") | |
| sys.exit(0) | |
| lint_collector = LintCollector(logger) | |
| parsed_bps = {} | |
| for android_bp in bps: | |
| content = None | |
| if getattr(args, "commit", None): | |
| content = _get_file_content_at_commit(android_bp, args.commit, root_paths, logger) | |
| parsed_bps[android_bp] = _lint_bp(pathlib.Path(android_bp), lint_collector, content=content) | |
| logger.info(f"{len(bps)} files checked:") | |
| for android_bp in bps: | |
| logger.info(f" {android_bp}") | |
| lint_collector.print_all() | |
| if lint_collector.fixes_available(): | |
| if args.no_fix: | |
| if args.all: | |
| bp_arg = "-a" | |
| else: | |
| bp_arg = ' '.join([str(bp) for bp in bps]) | |
| logger.warn( | |
| f"Errors found. Fix these by running: \n" | |
| f"{sys.argv[0]} pod lint -f {bp_arg}") | |
| else: | |
| apply_fixes = args.fix | |
| if not apply_fixes: | |
| yn = input("Fixes available. Would you like to apply them? (Y/n) ") or 'y' | |
| apply_fixes = yn.lower() == 'y' | |
| if apply_fixes: | |
| (num_fixes, fixed_bps) = lint_collector.apply_fixes(parsed_bps) | |
| for android_bp, parsed_bp in fixed_bps.items(): | |
| pathlib.Path(android_bp).write_text(bp.writer.write(parsed_bp)) | |
| logger.info(f"{num_fixes} fixes applied across {len(fixed_bps)} files.") | |
| if not lint_collector.has_findings(): | |
| logger.info("Everything checks out!") | |
| else: | |
| # Exit with error even if fixes were applied since we might not have fixed | |
| # everything. | |
| sys.exit(1) | |
| def _file_relative_to_paths(fp, root_paths, logger): | |
| bps = [] | |
| p = pathlib.Path(fp) | |
| if p.is_absolute(): | |
| candidates = [p] | |
| else: | |
| candidates = [pathlib.Path(root) / p for root in root_paths] | |
| for abs_path in candidates: | |
| resolved = abs_path.resolve() | |
| if not any( | |
| resolved.is_relative_to(_resolve_pod_dir(root, pod_dir)) | |
| for root in root_paths | |
| for pod_dir in POD_DIRECTORIES.values() | |
| ): | |
| # Only analyze bps in our pod directories. | |
| continue | |
| for root in root_paths: | |
| try: | |
| rel_path = resolved.relative_to(root) | |
| if rel_path not in bps: | |
| bps.append(rel_path) | |
| break | |
| except ValueError: | |
| continue | |
| else: | |
| logger.error(f"Error: File '{fp}' is not under search paths ({root_paths})") | |
| return bps | |
| def _get_commit_bp_files(commit_id, search_paths, root_paths): | |
| """Finds .bp files modified or added in the specified git commit under search_paths.""" | |
| bps = [] | |
| for search_path in search_paths: | |
| p = pathlib.Path(search_path).resolve() | |
| if not p.exists(): | |
| continue | |
| try: | |
| git_root_res = subprocess.run( | |
| ["git", "rev-parse", "--show-toplevel"], | |
| cwd=p, | |
| capture_output=True, text=True, check=True | |
| ) | |
| git_root = pathlib.Path(git_root_res.stdout.strip()) | |
| git_diff_res = subprocess.run( | |
| ["git", "diff-tree", "--no-commit-id", "--name-only", "-r", commit_id], | |
| cwd=git_root, | |
| capture_output=True, text=True, check=True | |
| ) | |
| for line in git_diff_res.stdout.splitlines(): | |
| file_part = line.strip() | |
| if not file_part.endswith(".bp"): | |
| continue | |
| abs_path = (git_root / file_part).resolve() | |
| if not any( | |
| abs_path.is_relative_to(_resolve_pod_dir(root, pod_dir)) | |
| for root in root_paths | |
| for pod_dir in POD_DIRECTORIES.values() | |
| ): | |
| continue | |
| for root in root_paths: | |
| try: | |
| rel_path = abs_path.relative_to(root) | |
| if rel_path not in bps: | |
| bps.append(rel_path) | |
| break | |
| except ValueError: | |
| continue | |
| except subprocess.CalledProcessError: | |
| continue | |
| return bps | |
| def _get_file_content_at_commit(android_bp, commit_id, root_paths, logger): | |
| """Reads the content of an Android.bp file from a git commit using git cat-file.""" | |
| abs_path = pathlib.Path(android_bp) | |
| if not abs_path.is_absolute(): | |
| for root in root_paths: | |
| candidate = (pathlib.Path(root) / abs_path).resolve() | |
| if candidate.exists(): | |
| abs_path = candidate | |
| break | |
| else: | |
| if root_paths: | |
| abs_path = (pathlib.Path(root_paths[0]) / abs_path).resolve() | |
| try: | |
| git_root_res = subprocess.run( | |
| ["git", "rev-parse", "--show-toplevel"], | |
| cwd=abs_path.parent, | |
| capture_output=True, text=True, check=True | |
| ) | |
| git_root = pathlib.Path(git_root_res.stdout.strip()) | |
| git_rel_path = abs_path.relative_to(git_root) | |
| cat_res = subprocess.run( | |
| ["git", "cat-file", "-p", f"{commit_id}:{git_rel_path}"], | |
| cwd=git_root, | |
| capture_output=True, text=True, check=True | |
| ) | |
| return cat_res.stdout | |
| except subprocess.CalledProcessError as e: | |
| logger.error(f"Error reading '{android_bp}' at commit {commit_id}: {e}") | |
| return None | |
| def _get_changed_bp_files(search_path, root_paths): | |
| """Finds modified, added, or untracked .bp files in the Git repository under search_path.""" | |
| bps = [] | |
| if not search_path.exists(): | |
| return bps | |
| try: | |
| git_root_res = subprocess.run( | |
| ["git", "rev-parse", "--show-toplevel"], | |
| cwd=search_path, | |
| capture_output=True, text=True, check=True | |
| ) | |
| git_root = pathlib.Path(git_root_res.stdout.strip()) | |
| git_status_res = subprocess.run( | |
| ["git", "status", "--porcelain", "-uall", str(search_path)], | |
| cwd=search_path, | |
| capture_output=True, text=True, check=True | |
| ) | |
| for line in git_status_res.stdout.splitlines(): | |
| if len(line) < 4: | |
| continue | |
| status = line[:2] | |
| file_part = line[3:] | |
| if "->" in file_part: | |
| file_part = file_part.split("->")[-1].strip() | |
| file_part = file_part.strip('"') | |
| abs_path = (git_root / file_part).resolve() | |
| if abs_path.suffix == ".bp" and abs_path.is_file(): | |
| for root in root_paths: | |
| try: | |
| rel_path = abs_path.relative_to(root) | |
| bps.append(rel_path) | |
| break | |
| except ValueError: | |
| continue | |
| except subprocess.CalledProcessError: | |
| return [] | |
| return bps | |
| def _lint_ast(parsed, android_bp, lint_collector): | |
| rel_path = None | |
| pod_base_dir = None | |
| for pod_base_dir in POD_DIRECTORIES.values(): | |
| try: | |
| rel_path = android_bp.relative_to(pod_base_dir) | |
| break | |
| except ValueError: | |
| pass | |
| for i in range(1, len(pod_base_dir.parts)): | |
| try: | |
| rel_path = android_bp.relative_to(pathlib.Path(*pod_base_dir.parts[i:])) | |
| break | |
| except ValueError: | |
| continue | |
| if rel_path is not None: | |
| break | |
| if android_bp.is_absolute(): | |
| for root in [pathlib.Path.cwd()]: | |
| candidate = _resolve_pod_dir(root, pod_base_dir) | |
| try: | |
| rel_path = android_bp.relative_to(candidate) | |
| break | |
| except ValueError: | |
| continue | |
| if rel_path is not None: | |
| break | |
| if rel_path is None: | |
| return | |
| if _disable_lint_for_file(parsed): | |
| return | |
| _check_api(pod_base_dir, rel_path, parsed, lint_collector) | |
| _check_copyright(pod_base_dir, rel_path, parsed, lint_collector) | |
| _check_dagger(pod_base_dir, rel_path, parsed, lint_collector) | |
| _check_impl(pod_base_dir, rel_path, parsed, lint_collector) | |
| _check_test(pod_base_dir, rel_path, parsed, lint_collector) | |
| _check_package_declaration(pod_base_dir, rel_path, parsed, lint_collector) | |
| _check_full_bp(pod_base_dir, rel_path, parsed, lint_collector) | |
| def _lint_bp(android_bp, lint_collector, content=None): | |
| parsed = bp.parser.parse(android_bp, content=content) | |
| _lint_ast(parsed, android_bp, lint_collector) | |
| return parsed | |
| def _check_api(pod_base_dir, android_bp_path, parsed, lint_collector): | |
| package_prefix = _package_prefix(pod_base_dir) | |
| expected_package_suffix = str(android_bp_path.parent).replace(os.path.sep, '.') | |
| expected_api_name = f"{package_prefix}{expected_package_suffix}_api" | |
| rules = [ | |
| AllowedPropertiesRule(), | |
| AlphabetizeListRule(["libs", "static_libs"]), | |
| ApiManifestNameRule(), | |
| ApiNameRule(expected_api_name), | |
| ApiNoImplDependenciesRule(), | |
| ModuleTypeRule(), | |
| PropertyOrderRule(), | |
| ] | |
| for module in _module_iterator(parsed, "_api"): | |
| for rule in rules: | |
| rule.checkModule(module, parsed, lint_collector, pod_base_dir, android_bp_path) | |
| def _check_copyright(pod_base_dir, android_bp, parsed, lint_collector): | |
| pass | |
| def _check_dagger(pod_base_dir, android_bp_path, parsed, lint_collector): | |
| package_prefix = _package_prefix(pod_base_dir) | |
| expected_package_suffix = str(android_bp_path.parent).replace(os.path.sep, '.') | |
| expected_dagger_name = f"{package_prefix}{expected_package_suffix}_dagger" | |
| rules = [ | |
| AllowedPropertiesRule(), | |
| AlphabetizeListRule(["libs", "static_libs"]), | |
| DaggerNameRule(expected_dagger_name), | |
| ModuleTypeRule(), | |
| PropertyOrderRule(), | |
| ] | |
| for module in _module_iterator(parsed, "_dagger"): | |
| for rule in rules: | |
| rule.checkModule(module, parsed, lint_collector, pod_base_dir, android_bp_path) | |
| def _check_impl(pod_base_dir, android_bp_path, parsed, lint_collector): | |
| package_prefix = _package_prefix(pod_base_dir) | |
| expected_package_suffix = str(android_bp_path.parent).replace(os.path.sep, '.') | |
| expected_impl_name = f"{package_prefix}{expected_package_suffix}_impl" | |
| expected_api_name = f"{package_prefix}{expected_package_suffix}_api" | |
| rules = [ | |
| AllowedPropertiesRule(), | |
| AlphabetizeListRule(["libs", "static_libs"]), | |
| ImplApiDependencyRule(expected_api_name), | |
| ImplManifestNameRule(), | |
| ImplNameRule(expected_impl_name), | |
| ImplOtherImplDependencyRule(), | |
| ModuleTypeRule(), | |
| PropertyOrderRule(), | |
| ] | |
| for module in _module_iterator(parsed, "_impl"): | |
| for rule in rules: | |
| rule.checkModule(module, parsed, lint_collector, pod_base_dir, android_bp_path) | |
| def _check_test(pod_base_dir, android_bp_path, parsed, lint_collector): | |
| package_prefix = _package_prefix(pod_base_dir) | |
| expected_package_suffix = str(android_bp_path.parent).replace(os.path.sep, '.') | |
| expected_test_name = f"{package_prefix}{expected_package_suffix}_testlib" | |
| rules = [ | |
| AllowedPropertiesRule(), | |
| AlphabetizeListRule(["libs", "static_libs"]), | |
| TestNameRule(expected_test_name), | |
| ModuleTypeRule(), | |
| PropertyOrderRule(), | |
| ] | |
| for module in _module_iterator(parsed, "_testlib"): | |
| for rule in rules: | |
| rule.checkModule(module, parsed, lint_collector, pod_base_dir, android_bp_path) | |
| def _check_full_bp(pod_base_dir, android_bp_path, parsed, lint_collector): | |
| rules = [ | |
| BpOrderRule(), | |
| ] | |
| for rule in rules: | |
| rule.checkFile(parsed, lint_collector, pod_base_dir, android_bp_path) | |
| def _check_package_declaration(pod_base_dir, android_bp_path, parsed, lint_collector): | |
| pass | |
| def _package_prefix(pod_base_dir): | |
| # Returns the leading package prefix (e.g. com.android.systemui.) based on the directory | |
| # that a pod is located in, or None if it is not in a pod directory. | |
| return next((k for k, v in POD_DIRECTORIES.items() | |
| if pathlib.Path(v) == pod_base_dir), None) | |
| def _module_iterator(parsed, name_suffix): | |
| for module in parsed: | |
| if not isinstance(module, bp.parser.Module): | |
| continue | |
| name_prop = module.get("name") | |
| if not name_prop: | |
| continue | |
| name = name_prop.value.value | |
| if not name.endswith(name_suffix): | |
| continue | |
| if module.module_type == "java_defaults": | |
| continue | |
| yield module | |
| def _disable_lint_for_file(parsed): | |
| for entry in parsed: | |
| disable_lint_instruction = _disable_lint_instruction(entry) | |
| if disable_lint_instruction is None: | |
| continue | |
| if disable_lint_instruction == "whole-file": | |
| return True | |
| return False | |
| def _disable_lint_instruction(entry): | |
| if not isinstance(entry, bp.parser.EndComment): | |
| return None | |
| text = entry.text.strip() | |
| if not text.startswith(LINT_DISABLE_PREFIX): | |
| return None | |
| return text[len(LINT_DISABLE_PREFIX):].strip() |