blob: 539c1b4ba49cb879c996d4ac650cbea65cf55828 [file]
# 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 collections
import dataclasses
import datetime
import os
import pathlib
import subprocess
import sys
from xml.sax import saxutils
from bp import composer
from bp import parser
from bp import writer
from . import lint
from .constants import POD_DIRECTORIES
from .lint_collector import LintCollector
TEMPLATE_DIRECTORY = pathlib.Path("templates")
if "ANDROID_BUILD_TOP" in os.environ:
TEMPLATE_DIRECTORY = (pathlib.Path(os.environ["ANDROID_BUILD_TOP"]) /
"frameworks/base/packages/SystemUI/scripts/sysui/templates")
DEFAULT_MODULES = ["api", "impl"]
MODULE_CHOICES = [
"api",
"api-manifest",
"api-res",
"dagger",
"impl",
"manifest",
"preview",
"preview-manifest",
"preview-res",
"res",
"test",
"test-fixtures",
"test-manifest",
"test-res",
]
def initialize_cmd(subparsers):
create_parser = subparsers.add_parser(
"create",
help="Create a new pod"
)
create_parser.set_defaults(func=create)
create_parser.add_argument(
"name",
help="""Full package name for the pod. Example: com.android.systemui.foo.bar
Everything after the "com.android.systemui" will be turned into a directory structure: foo/bar.
Entering com.android.systemui creates the pod in AOSP. Entering com.google.android.systemui creates
the pod in SystemUIGoogle. Other packages are not supported.
"""
)
def comma_separated(arg):
return arg.split(",")
create_parser.add_argument(
"-m", "--modules",
type=comma_separated,
help="Comma separated list of modules to create for the pod. Defaults to 'api,impl'.\n"
"Options: " + ",".join(MODULE_CHOICES)
)
create_parser.add_argument(
"-o", "--owners",
type=comma_separated,
help="Comma separated list of emails to add to the OWNERS file. Defaults to "
"`git config get user.email`."
)
create_parser.add_argument(
"-b", "--buganizer-component",
type=int,
help="""Buganizer Component Id. Required when creating (but not updating) a new pod."""
)
def create(args, logger):
name = args.name
if not any(name.startswith(p) for p in POD_DIRECTORIES.keys()):
invalid = True
if not name.startswith("com."):
name = f"com.android.systemui.{name}"
inp = input(
f"Full package name not provided. Assuming ASOP - \"{name}\". Accept? [Y/n]")
inp = inp or "y"
if inp.lower() == "y":
invalid = False
if invalid:
print(
"Invalid package. Must start with one of:\n "
+ "\n ".join(POD_DIRECTORIES.keys()),
file=sys.stderr
)
sys.exit(-1)
modules = args.modules or DEFAULT_MODULES
for m in modules:
if m not in MODULE_CHOICES:
print(
f"Invalid module typ {m}. Must be one of {','.join(MODULE_CHOICES)}",
file=sys.stderr
)
sys.exit(-1)
base_package = next((p for p in POD_DIRECTORIES.keys() if name.startswith(p)))
sub_package = name[len(base_package):]
base_directory = POD_DIRECTORIES[base_package]
pod_info = PodInfo(
base_directory=base_directory,
sub_package=sub_package,
name=name,
owners=args.owners,
buganizer_component=args.buganizer_component
)
_create(pod_info, modules, logger)
def _create(pod_info, modules, logger):
create_base(pod_info)
android_bp = parser.parse(pod_info.bp_path)
api_processed = False
impl_processed = False
preview_processed = False
test_processed = False
for m in modules:
if _has_module(pod_info.name, m, android_bp):
continue
if m == "api" or m == "api-manifest" or m == "api-res":
if not api_processed:
create_api(
pod_info,
android_bp,
with_manifest="api-manifest" in modules,
with_res="api-res" in modules
)
api_processed = True
elif m == "dagger":
create_dagger(pod_info, android_bp)
elif m == "impl" or m == "manifest" or m == "res":
if not impl_processed:
create_impl(
pod_info,
android_bp,
with_manifest="manifest" in modules,
with_res="res" in modules
)
main_processed = True
elif m == "preview" or m == "preview-manifest" or m == "preview-res":
if not preview_processed:
create_preview(
pod_info,
android_bp,
with_manifest="preview-manifest" in modules,
with_res="preview-res" in modules
)
preview_processed = True
elif m == "test" or m == "test-manifest" or m == "test-res":
if not test_processed:
create_test(
pod_info,
android_bp,
with_manifest="test-manifest" in modules,
with_res="test-res" in modules
)
test_processed = True
elif m == "test-fixtures":
create_test_fixtures(pod_info, android_bp)
else:
print(f"Module type not yet implemented: {m}")
# Run lint on the raw AST before it is written to disk, with fixes turned on.
lint_collector = LintCollector(logger=logger)
lint._lint_ast(android_bp, pod_info.bp_path, lint_collector)
if lint_collector.fixes_available():
_, fixed_bps = lint_collector.apply_fixes({pod_info.bp_path: android_bp})
if pod_info.bp_path in fixed_bps:
android_bp = fixed_bps[pod_info.bp_path]
# Then write to disk.
pod_info.bp_path.write_text(writer.write(android_bp))
# Finally, run lint with fixes turned off on the written file.
final_collector = LintCollector(logger=logger)
lint._lint_bp(pod_info.bp_path, final_collector)
# Print a warning if any lint issues are found.
if final_collector.has_findings():
failures_str = final_collector.formatted_results()
warning_msg = (
"The generated pod is contains unexpected lint failures. "
"Please file a bug at http://b/issues/new?component=1203176, and include the below failures for reference:\n\n"
f"{failures_str}"
)
print(warning_msg, file=sys.stderr)
def create_base(pod_info):
p = pod_info.path
p.mkdir(parents=True, exist_ok=True)
if not pod_info.bp_path.is_file():
pod_info.bp_path.write_text(
_simple_template_fill("Android.bp.tpl", year=datetime.datetime.now().year)
)
has_errors = False
owners = pod_info.owners
if not (p / "OWNERS").is_file():
if pod_info.buganizer_component is None:
print("Must specify a buganizer-component when creating a new pod.",
file=sys.stderr)
has_errors = True
if not owners:
result = subprocess.run(
["git", "config", "get", "user.email"], text=True, capture_output=True)
if result.returncode != 0:
print(
"Failed to obtain email for owners. Please specify one explicitly with -o",
file=sys.stderr)
has_errors = True
else:
owners = [result.stdout.strip()]
if owners and pod_info.buganizer_component is not None:
(p / "OWNERS").write_text(_simple_template_fill(
"OWNERS.tpl",
bug_component_id=pod_info.buganizer_component,
usernames="\n".join(owners)))
else:
if owners:
print("Can not specify owners when the file already exists. Please update it manually.",
file=sys.stderr)
has_errors = True
if pod_info.buganizer_component is not None:
print("Can not specify buganizer-component when the file already exists. "
"Please update it manually.",
file=sys.stderr)
has_errors = True
if has_errors:
sys.exit(-1)
return p
def _update_module_common(
module, directory, pod_type, package_name, with_manifest, with_res, additional_props=None):
module_type = "java_library"
props = {
"defaults": [_module_defaults(pod_type)],
}
props.update(additional_props or {})
_create_src_dir(directory, pod_type)
manifest_name = f"{pod_type.capitalize()}AndroidManifest.xml"
if pod_type == "impl":
manifest_name = f"AndroidManifest.xml"
res_dir = f"{pod_type}Res"
if pod_type == "impl":
res_dir = "res"
manifest_path = directory / manifest_name
# If the manifest already exists, keep it.
with_manifest = with_manifest or manifest_path.is_file()
# If the res already exists, keep it.
with_res = with_res or _src_dir(directory, res_dir).is_dir()
is_android = with_manifest or with_res
if is_android:
module_type = "android_library"
if with_manifest:
if not manifest_path.is_file():
_write_manifest(package_name, manifest_path)
props["manifest"] = manifest_name
if with_res:
_create_src_dir(directory, res_dir)
props["resource_dirs"] = _keep_sorted(f"src/{res_dir}")
if not with_manifest:
props["package_name"] = package_name
if module is None:
module = composer.composeModule(
module_type,
_module_name(package_name, pod_type),
props
)
else:
module.module_type = module_type
module = composer.addProperties(module, props, update=True)
return module
def create_api(pod_info, android_bp, with_manifest=False, with_res=False):
name = pod_info.name
directory = pod_info.path
api_module = _get_module(name, "api", android_bp)
is_new = api_module is None
api_module = _update_module_common(
api_module,
directory,
"api",
name,
with_manifest,
with_res,
additional_props={"libs": _keep_sorted()})
if is_new:
android_bp.append(api_module)
android_bp.append(parser.BlankLine())
else:
composer.upsert_module(api_module, android_bp)
# The impl needs to be updated to include the new api.
impl_module = _get_module(name, "impl", android_bp)
if impl_module is not None:
static_libs = impl_module.get("static_libs", parser.List([]))
if parser.String(_module_name(name, "api")) not in static_libs.value:
static_libs.value.append(parser.String(_module_name(name, "api")))
static_libs = parser.List(static_libs.value)
impl_module = composer.addProperties(impl_module, {"static_libs": static_libs}, update=True)
composer.upsert_module(impl_module, android_bp)
return api_module
def create_dagger(pod_info, android_bp):
name = pod_info.name
dagger_module = _get_module(name, "dagger", android_bp)
# The dagger module is not updatable. It has only one form that either exists or doesn't.
if dagger_module is not None:
return dagger_module
create_api(pod_info, android_bp)
create_impl(pod_info, android_bp)
dagger_module = _update_module_common(
None,
pod_info.path,
"dagger",
name,
with_manifest=False,
with_res=False,
additional_props={"static_libs": _keep_sorted(
_module_name(name, "api"),
_module_name(name, "impl"),
)}
)
android_bp.append(dagger_module)
android_bp.append(parser.BlankLine())
return dagger_module
def create_impl(pod_info, android_bp, with_manifest=False, with_res=False):
name = pod_info.name
impl_module = _get_module(name, "impl", android_bp)
has_api = _has_module(name, "api", android_bp)
static_libs = []
if has_api:
static_libs += [_module_name(name, "api")]
is_new = impl_module is None
impl_module = _update_module_common(
impl_module,
pod_info.path,
"impl",
name,
with_manifest,
with_res,
additional_props={"static_libs": _keep_sorted(*static_libs)}
)
if is_new:
android_bp.append(impl_module)
android_bp.append(parser.BlankLine())
else:
composer.upsert_module(impl_module, android_bp)
return impl_module
def create_preview(pod_info, android_bp, with_manifest=False, with_res=False):
name = pod_info.name
preview_module = _get_module(name, "preview", android_bp)
create_impl(pod_info, android_bp)
is_new = preview_module is None
preview_module = _update_module_common(
preview_module,
pod_info.path,
"preview",
name,
with_manifest,
with_res,
additional_props={"static_libs": _keep_sorted(_module_name(name, "impl"))}
)
if is_new:
android_bp.append(preview_module)
else:
composer.upsert_module(preview_module, android_bp)
return preview_module
def create_test(pod_info, android_bp, with_manifest=False, with_res=False):
name = pod_info.name
test_module = _get_module(name, "testlib", android_bp)
create_api(pod_info, android_bp)
create_impl(pod_info, android_bp)
is_new = test_module is None
test_module = _update_module_common(
test_module,
pod_info.path,
"test",
name,
with_manifest,
with_res,
additional_props={"static_libs": _keep_sorted(
_module_name(name, "api"),
_module_name(name, "impl"),
)}
)
if is_new is None:
android_bp.append(test_module)
android_bp.append(parser.BlankLine())
else:
composer.upsert_module(test_module, android_bp)
return test_module
def create_test_fixtures(pod_info, android_bp):
name = pod_info.name
directory = pod_info.path
_create_src_dir(directory, "testFixtures")
fixtures_module = _get_module(name, "fixtureFiles", android_bp)
if fixtures_module is not None:
return fixtures_module
fixtures_module = composer.composeModule(
"filegroup",
_module_name(name, "fixtureFiles"),
collections.OrderedDict([
("defaults", [_module_defaults("fixtureFiles")]),
])
)
android_bp.append(fixtures_module)
android_bp.append(parser.BlankLine())
return fixtures_module
@dataclasses.dataclass
class PodInfo:
base_directory: str
sub_package: str
name: str
owners: list
buganizer_component: int
@property
def path(self):
return pathlib.Path(self.base_directory / self.sub_package.replace('.', '/'))
@property
def bp_path(self):
return self.path / "Android.bp"
def _has_module(name, type, android_bp):
return _get_module(name, type, android_bp) is not None
def _get_module(name, type, android_bp):
for m in android_bp:
if not isinstance(m, parser.Module):
continue
if "name" not in m:
continue # Assume modules without names are not for us to mess with, like `package`
if m["name"].value.value == _module_name(name, type):
return m
return None
def _module_name(name, pod_type):
if pod_type == "test":
pod_type = "testlib"
return f"{name}_{pod_type}"
def _module_defaults(pod_type):
if pod_type == "test":
pod_type = "testlib"
return f"sysui_{pod_type}"
def _keep_sorted(*args):
return ([parser.EndComment("// go/keep-sorted start")]
+ list(args)
+ [parser.EndComment("// go/keep-sorted end")])
def _simple_template_fill(template, /, **kwargs):
with open(TEMPLATE_DIRECTORY / template) as tpl:
content = tpl.read()
return content.format(
**kwargs
)
def _write_manifest(package_name, manifest_path):
manifest_path.write_text(
_simple_template_fill(
"AndroidManifest.xml.tpl",
year=datetime.datetime.now().year,
package_name=saxutils.quoteattr(package_name)
)
)
def _src_dir(directory, name):
return directory / "src" / name
def _create_src_dir(directory, name):
_src_dir(directory, name).mkdir(parents=True, exist_ok=True)