Delete bazel_rules_fuchsia
The rules have been moved into fuchsia.git. Changes to the rules should
now be made there.
Change-Id: I63535e8450773722e734b37111dbd2b63b6e7df1
Reviewed-on: https://fuchsia-review.googlesource.com/c/sdk-integration/+/792756
Reviewed-by: Jiaming Li <lijiaming@google.com>
Commit-Queue: Chase Latta <chaselatta@google.com>
diff --git a/README.md b/README.md
index 73dd079..e2d7dcd 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,10 @@
Fuchsia SDK Integration Repository
==================================
+This repository is in the process of moving to fuchsia.git.
+
This repository provides environment-specific (e.g. Bazel, GN) tools
for the SDK and associated integration tests in a public repo.
Visit [Contributing to Fuchsia](https://fuchsia.dev/fuchsia-src/CONTRIBUTING)
-to learn how to contribute to this repository.
\ No newline at end of file
+to learn how to contribute to this repository.
diff --git a/bazel_rules_fuchsia/BUILD.bazel b/bazel_rules_fuchsia/BUILD.bazel
deleted file mode 100644
index b7c657c..0000000
--- a/bazel_rules_fuchsia/BUILD.bazel
+++ /dev/null
@@ -1,16 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load("//fuchsia/private:debug_info.bzl", "print_debug_info")
-
-# A target that will dump debug information about the Fuchsia
-# Bazel SDK and tools that it is using.
-#
-# Note: this command relies on the existence of a fuchsia_clang repository being
-# registered in your WORKSPACE file.
-#
-# bazel run @rules_fuchsia//:debug_info
-print_debug_info(
- name = "debug_info",
-)
diff --git a/bazel_rules_fuchsia/MODULE.bazel b/bazel_rules_fuchsia/MODULE.bazel
deleted file mode 100644
index 89bbd7f..0000000
--- a/bazel_rules_fuchsia/MODULE.bazel
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-module(
- name = "rules_fuchsia",
- version = "0.0.1",
- #TODO(fxbug.dev/108139) add bazel_compatibility when it is ready
-)
-
-# Required Dependencies
-bazel_dep(name = "bazel_skylib", version = "1.2.0")
-bazel_dep(name = "rules_cc", version = "0.0.1")
-bazel_dep(name = "platforms", version = "0.0.6")
-bazel_dep(name = "rules_python", version = "0.10.2")
-
-# Setup the cipd_tool repo for downloading content
-cipd_tool_ext = use_extension("//cipd:defs.bzl", "cipd_tool_ext")
-cipd_tool_ext.client(bin = "foo_tool")
-use_repo(cipd_tool_ext, "cipd_tool")
-
-# Declare the fuchsia sdk
-fuchsia_sdk_ext = use_extension("//fuchsia:deps.bzl", "fuchsia_sdk_ext")
-use_repo(fuchsia_sdk_ext, "fuchsia_sdk")
-
-register_toolchains("@fuchsia_sdk//:fuchsia_toolchain_sdk")
-
-# Declare clang
-fuchsia_clang_ext = use_extension("//fuchsia:deps.bzl", "fuchsia_clang_ext")
-use_repo(fuchsia_clang_ext, "fuchsia_clang")
-
-register_toolchains("@fuchsia_clang//:cc-x86_64")
-
-register_toolchains("@fuchsia_clang//:cc-aarch64")
diff --git a/bazel_rules_fuchsia/README.md b/bazel_rules_fuchsia/README.md
index 9a25db6..5539d6b 100644
--- a/bazel_rules_fuchsia/README.md
+++ b/bazel_rules_fuchsia/README.md
@@ -1,10 +1,11 @@
# Fuchsia Bazel SDK
-This directory contains the contents of the Fuchsia Bazel SDK. The Fuchsia Bazel
-SDK is a set of rules which aid in the development of Fuchsia packages and products.
+The Starlark code was moved into the fuchsia.git tree with the
+<https://fuchsia-review.git.corp.google.com/c/fuchsia/+/793913> commit.
-## Directory layout
+The rules can be found at <https://cs.opensource.google/fuchsia/fuchsia/+/main:build/bazel_sdk>
-* `fuchsia` — Bazel build rules.
-* `tools` — Tools used by Bazel rules and targets.
+This file still contains the scripts and tools directories since they are
+being used for OOT repositories. They will be moved to another repo at a later
+time.
diff --git a/bazel_rules_fuchsia/WORKSPACE.bazel b/bazel_rules_fuchsia/WORKSPACE.bazel
deleted file mode 100644
index 0ae70c1..0000000
--- a/bazel_rules_fuchsia/WORKSPACE.bazel
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Workspace definition for rules_fuchsia.git s
-
-workspace(name = "rules_fuchsia")
-
-load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
-load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
-
-# Stardoc documentation generator
-# https://github.com/bazelbuild/stardoc
-
-git_repository(
- name = "io_bazel_stardoc",
- commit = "4378e9b6bb2831de7143580594782f538f461180",
- remote = "https://github.com/bazelbuild/stardoc.git",
- shallow_since = "1570829166 -0400",
-)
-
-load("@io_bazel_stardoc//:setup.bzl", "stardoc_repositories")
-
-stardoc_repositories()
-
-# Bazel Skylib; Starlark utilities
-# https://github.com/bazelbuild/bazel-skylib
-
-http_archive(
- name = "bazel_skylib",
- sha256 = "1c531376ac7e5a180e0237938a2536de0c54d93f5c278634818e0efc952dd56c",
- urls = [
- "https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.3/bazel-skylib-1.0.3.tar.gz",
- "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.0.3/bazel-skylib-1.0.3.tar.gz",
- ],
-)
-
-load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
-
-bazel_skylib_workspace()
-
-load(
- "@rules_fuchsia//fuchsia:deps.bzl",
- "fuchsia_sdk_repository",
- "rules_fuchsia_deps",
-)
-
-rules_fuchsia_deps()
-
-fuchsia_sdk_repository(
- name = "fuchsia_sdk",
-)
-
-register_toolchains("@fuchsia_sdk//:fuchsia_toolchain_sdk")
-
-load("@rules_fuchsia//fuchsia:workspace_setup.bzl", "rules_fuchsia_workspace_setup")
-
-rules_fuchsia_workspace_setup()
diff --git a/bazel_rules_fuchsia/WORKSPACE.bzlmod b/bazel_rules_fuchsia/WORKSPACE.bzlmod
deleted file mode 100644
index fafa28d..0000000
--- a/bazel_rules_fuchsia/WORKSPACE.bzlmod
+++ /dev/null
@@ -1,2 +0,0 @@
-# When Bzlmod is enabled, this file replaces the content of the original WORKSPACE
-# and makes sure no WORKSPACE prefix or suffix are added when Bzlmod is enabled.
diff --git a/bazel_rules_fuchsia/cipd/BUILD.bazel b/bazel_rules_fuchsia/cipd/BUILD.bazel
deleted file mode 100644
index 45d8e6a..0000000
--- a/bazel_rules_fuchsia/cipd/BUILD.bazel
+++ /dev/null
@@ -1,3 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
diff --git a/bazel_rules_fuchsia/cipd/defs.bzl b/bazel_rules_fuchsia/cipd/defs.bzl
deleted file mode 100644
index 3099759..0000000
--- a/bazel_rules_fuchsia/cipd/defs.bzl
+++ /dev/null
@@ -1,21 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- "//cipd/private:cipd_tool.bzl",
- _cipd_tool_ext = "cipd_tool_ext",
- _cipd_tool_repository = "cipd_tool_repository",
-)
-load(
- "//cipd/private:cipd_repository.bzl",
- _cipd_repository = "cipd_repository",
- _fetch_cipd_contents = "fetch_cipd_contents",
- _fetch_cipd_contents_from_https = "fetch_cipd_contents_from_https",
-)
-
-cipd_repository = _cipd_repository
-cipd_tool_ext = _cipd_tool_ext
-cipd_tool_repository = _cipd_tool_repository
-fetch_cipd_contents = _fetch_cipd_contents
-fetch_cipd_contents_from_https = _fetch_cipd_contents_from_https
diff --git a/bazel_rules_fuchsia/cipd/private/BUILD.bazel b/bazel_rules_fuchsia/cipd/private/BUILD.bazel
deleted file mode 100644
index 45d8e6a..0000000
--- a/bazel_rules_fuchsia/cipd/private/BUILD.bazel
+++ /dev/null
@@ -1,3 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
diff --git a/bazel_rules_fuchsia/cipd/private/cipd_digests/BUILD.bazel b/bazel_rules_fuchsia/cipd/private/cipd_digests/BUILD.bazel
deleted file mode 100644
index 535b0be..0000000
--- a/bazel_rules_fuchsia/cipd/private/cipd_digests/BUILD.bazel
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# These files can be updated by calling
-# cipd selfupdate-roll -version-file cipd/private/cipd_digests/cipd_client_version -version <NEW_VERSION>
-exports_files([
- "cipd_client_version",
- "cipd_client_version.digests",
-])
diff --git a/bazel_rules_fuchsia/cipd/private/cipd_digests/cipd_client_version b/bazel_rules_fuchsia/cipd/private/cipd_digests/cipd_client_version
deleted file mode 100644
index b79be6d..0000000
--- a/bazel_rules_fuchsia/cipd/private/cipd_digests/cipd_client_version
+++ /dev/null
@@ -1 +0,0 @@
-git_revision:4511c670f851c56473a7370c10c199cdad4dfc3c
diff --git a/bazel_rules_fuchsia/cipd/private/cipd_digests/cipd_client_version.digests b/bazel_rules_fuchsia/cipd/private/cipd_digests/cipd_client_version.digests
deleted file mode 100644
index 4433b82..0000000
--- a/bazel_rules_fuchsia/cipd/private/cipd_digests/cipd_client_version.digests
+++ /dev/null
@@ -1,23 +0,0 @@
-# This file was generated by
-#
-# cipd selfupdate-roll -version-file cipd_client_version \
-# -version git_revision:4511c670f851c56473a7370c10c199cdad4dfc3c
-#
-# Do not modify manually. All changes will be overwritten.
-# Use 'cipd selfupdate-roll ...' to modify.
-
-aix-ppc64 sha256 0696f6979153a326f5269ac24cc03a834de8472fc35d467efe13618d30186332
-linux-386 sha256 0299c0a3b1a86bccfb1ef974b981827649a64c42406205126e789b7cba466839
-linux-amd64 sha256 d2ef210cdcc2df1f3d0c74c5918999088426490ed000f009ebd7fdaec1f77222
-linux-arm64 sha256 98ccdf942ecee4744aa6469e4093e025983d005f9a22e34c0d35d70accc77351
-linux-armv6l sha256 b74057db288278ccaa67bb444b5e6e84dbef0912636ca06fadf10f3f98c04ebe
-linux-mips64 sha256 1850c72d660bf1096b827aad422927fedc2f61428ff89c7f50ff05340bc226e1
-linux-mips64le sha256 ceb9571d9fbcdd70d3744e96f69c55c53b2feec60b6326d59141a2a308acc87c
-linux-mipsle sha256 07d1ecba6e9b33fdf7b5c31e82768579ee8633caeb439a566e3d8bdda589b575
-linux-ppc64 sha256 cffb1bd349b6eb53389d3318b88c73cf73fd8b56897f53a0bad455fbeacf501b
-linux-ppc64le sha256 e021b4f6442a2b88018f008c6969776b4cc2c592de9107c07a43f182ef51e169
-linux-s390x sha256 e91fe9df5b17bbefbe098a661581e3c61b940f5ec0303320d929ab86a6c4645c
-mac-amd64 sha256 d4e065720036cd381810e8503fa4c6cc45d69c19179ab35ba4eb0969a8580341
-mac-arm64 sha256 e4f78c9d58ab982419abcb5153f69050eeab7d28cac55ce8e8a9e12f822c2055
-windows-386 sha256 b761be1d35aa0d3b63a1aeaaf9a4952447fa7ea681e84dce603980a176092f17
-windows-amd64 sha256 53baa50b2f7cdcaa0e15510a2fd0debc0297db7914d848e209779ae74aaa3931
diff --git a/bazel_rules_fuchsia/cipd/private/cipd_repository.bzl b/bazel_rules_fuchsia/cipd/private/cipd_repository.bzl
deleted file mode 100644
index 757ce1c..0000000
--- a/bazel_rules_fuchsia/cipd/private/cipd_repository.bzl
+++ /dev/null
@@ -1,61 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":cipd_tool.bzl", "cipd_tool_repository")
-load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe", "workspace_and_buildfile")
-
-# Base URL for CIPD archives.
-_CIPD_URL_TEMPLATE = "https://chrome-infra-packages.appspot.com/dl/{package_path}/{os}-{arch}/+/{tag}"
-
-def cipd_repository(name, ensure_file, **kwargs):
- # Verify that we have a cipd tool repo
- maybe(
- name = "cipd_tool",
- repo_rule = cipd_tool_repository,
- )
- _cipd_repository(name = name, ensure_file = ensure_file, **kwargs)
-
-def fetch_cipd_contents(repository_ctx, cipd_bin, ensure_file, root = "."):
- result = repository_ctx.execute(
- [
- repository_ctx.path(cipd_bin),
- "ensure",
- "-ensure-file",
- repository_ctx.path(ensure_file),
- "-root",
- root,
- "-max-threads=0",
- ],
- )
- if result.return_code != 0:
- fail("Unable to download cipd content for {}\n{}".format(ensure_file, result.stderr))
-
-def _https_url(package_path, os, arch, tag):
- return _CIPD_URL_TEMPLATE.format(package_path = package_path, os = os, arch = arch, tag = tag)
-
-def fetch_cipd_contents_from_https(repository_ctx, package_path, os, arch, tag, sha256 = "", root = "."):
- result = repository_ctx.download_and_extract(
- _https_url(package_path, os, arch, tag),
- type = "zip",
- sha256 = sha256,
- output = root,
- )
-
- return result.sha256
-
-def _cipd_repository_impl(repository_ctx):
- fetch_cipd_contents(repository_ctx, repository_ctx.attr.cipd_bin, repository_ctx.attr.ensure_file)
- workspace_and_buildfile(repository_ctx)
-
-_cipd_repository = repository_rule(
- implementation = _cipd_repository_impl,
- attrs = {
- "ensure_file": attr.label(allow_files = True),
- "cipd_bin": attr.label(default = "@cipd_tool//:cipd"),
- "workspace_file": attr.label(),
- "workspace_file_content": attr.string(),
- "build_file": attr.label(),
- "build_file_content": attr.string(),
- },
-)
diff --git a/bazel_rules_fuchsia/cipd/private/cipd_tool.bzl b/bazel_rules_fuchsia/cipd/private/cipd_tool.bzl
deleted file mode 100644
index 18bbe8f..0000000
--- a/bazel_rules_fuchsia/cipd/private/cipd_tool.bzl
+++ /dev/null
@@ -1,128 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""CIPD repository rule utilities."""
-
-load("//fuchsia/workspace:utils.bzl", "workspace_path")
-
-_CIPD_GLOBAL_BIN_ENV = "CIPD_BIN"
-
-def _verify_cipd_bin(repository_ctx, bin):
- exec_result = repository_ctx.execute([
- bin,
- "--version",
- ])
-
- if exec_result.return_code != 0:
- fail("Invalid cipd binary provided ")
-
-def _setup_from_path(repository_ctx, path):
- bin = repository_ctx.path(path)
-
- if repository_ctx.attr.validate_cipd_bin:
- _verify_cipd_bin(repository_ctx, bin)
-
- repository_ctx.symlink(bin, "cipd")
-
-def _platform(repository_ctx):
- os = repository_ctx.os
- name = os.name.split(" ")[0].lower()
- arch = os.arch
- if arch == "x86_64":
- arch = "amd64"
- elif arch == "aarch64":
- arch = "arm64"
-
- return "{}-{}".format(name, arch)
-
-def _cipd_revision(repository_ctx):
- version_file = repository_ctx.attr._cipd_client_version
- rev = repository_ctx.read(version_file)
- return rev
-
-def _sha_for_platform(repository_ctx, platform):
- digests_file = repository_ctx.attr._cipd_client_version_digests
- digests = repository_ctx.read(digests_file)
- for line in digests.splitlines():
- if line.startswith("#"):
- continue
-
- # split(" ") will include the blanks so we need to split and then
- # strip out the blanks
- parts = []
- for part in line.split(" "):
- if part != "":
- parts.append(part)
- if len(parts) == 3 and parts[0] == platform:
- return parts[2]
-
- return None
-
-def _download_cipd_binary(repository_ctx):
- platform = _platform(repository_ctx)
- rev = _cipd_revision(repository_ctx)
- url = "https://chrome-infra-packages.appspot.com/client?platform={}&version={}".format(platform, rev)
- sha = _sha_for_platform(repository_ctx, platform)
-
- if sha == None:
- fail("unsupported cipd platform {}".format(platform))
-
- repository_ctx.download(
- url,
- executable = True,
- output = "cipd",
- sha256 = sha,
- )
-
-def _cipd_tool_repository_impl(repository_ctx):
- if repository_ctx.attr.bin:
- bin_path = workspace_path(repository_ctx, repository_ctx.attr.bin)
- _setup_from_path(repository_ctx, bin_path)
- elif repository_ctx.os.environ.get(_CIPD_GLOBAL_BIN_ENV):
- _setup_from_path(
- repository_ctx,
- repository_ctx.os.environ.get(_CIPD_GLOBAL_BIN_ENV),
- )
- else:
- _download_cipd_binary(repository_ctx)
-
- repository_ctx.file("WORKSPACE.bazel", content = " ")
- repository_ctx.file("BUILD.bazel", content = 'exports_files(glob(["**/*"]) )')
-
-cipd_tool_repository = repository_rule(
- implementation = _cipd_tool_repository_impl,
- attrs = {
- "bin": attr.string(doc = "The path to the cipd binary"),
- "validate_cipd_bin": attr.bool(
- doc = "Whether we should validate that the cipd binary is valid",
- default = True,
- ),
- "_cipd_client_version": attr.label(default = "//cipd/private/cipd_digests:cipd_client_version"),
- "_cipd_client_version_digests": attr.label(default = "//cipd/private/cipd_digests:cipd_client_version.digests"),
- },
-)
-
-def _cipd_tool_repository_ext_impl(ctx):
- bin = None
- for mod in ctx.modules:
- # Only allow the root module to set the binary.
- if mod.is_root:
- # Check to see if the root set the bin to use.
- client_tags = mod.tags.client
- if len(client_tags) == 2:
- fail("only one client tag may be specified at a time")
- elif len(client_tags) == 1:
- bin = client_tags[0].bin
-
- cipd_tool_repository(
- name = "cipd_tool",
- bin = bin,
- )
-
-_cipd_client_tag = tag_class(attrs = {"bin": attr.string()})
-
-cipd_tool_ext = module_extension(
- implementation = _cipd_tool_repository_ext_impl,
- tag_classes = {"client": _cipd_client_tag},
-)
diff --git a/bazel_rules_fuchsia/fuchsia/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/BUILD.bazel
deleted file mode 100644
index 9ed9684..0000000
--- a/bazel_rules_fuchsia/fuchsia/BUILD.bazel
+++ /dev/null
@@ -1,31 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Public Fuchsia rules.
-
-load("//fuchsia/private:flags.bzl", "package_repo_path_flag")
-
-# Toolchain type for the Fuchsia toolchain.
-toolchain_type(
- name = "toolchain",
- visibility = ["//visibility:public"],
-)
-
-# Export files for use in documentation.
-exports_files(
- glob(["*.bzl"]),
- visibility = ["//:__subpackages__"],
-)
-
-# Command line flags
-
-# Allows the user to specify a path to a package repository
-# which packages can be published to.
-#
-# bazel build //:my_package --@rules_fuchsia//fuchsia:package_repo=out/foo
-package_repo_path_flag(
- name = "package_repo",
- build_setting_default = "",
- visibility = ["//visibility:public"],
-)
diff --git a/bazel_rules_fuchsia/fuchsia/assembly.bzl b/bazel_rules_fuchsia/fuchsia/assembly.bzl
deleted file mode 100644
index 8b5161e..0000000
--- a/bazel_rules_fuchsia/fuchsia/assembly.bzl
+++ /dev/null
@@ -1,203 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Public definitions for Assembly related rules."""
-
-load(
- "//fuchsia/private/assembly:fuchsia_prebuilt_package.bzl",
- _fuchsia_prebuilt_package = "fuchsia_prebuilt_package",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_assemble_package.bzl",
- _fuchsia_assemble_package = "fuchsia_assemble_package",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_images_configuration.bzl",
- _fuchsia_images_configuration = "fuchsia_images_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_product_image.bzl",
- _fuchsia_product_image = "fuchsia_product_image",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_platform_input_configuration.bzl",
- _INPUT_DEVICE_TYPE = "INPUT_DEVICE_TYPE",
- _fuchsia_platform_input_configuration = "fuchsia_platform_input_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_platform_connectivity_configuration.bzl",
- _fuchsia_platform_connectivity_configuration = "fuchsia_platform_connectivity_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_platform_connectivity_wlan_configuration.bzl",
- _fuchsia_platform_connectivity_wlan_configuration = "fuchsia_platform_connectivity_wlan_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_platform_development_support_configuration.bzl",
- _fuchsia_platform_development_support_configuration = "fuchsia_platform_development_support_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_platform_starnix_configuration.bzl",
- _fuchsia_platform_starnix_configuration = "fuchsia_platform_starnix_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_platform_identity_configuration.bzl",
- _FEATURE_CONTROL = "FEATURE_CONTROL",
- _fuchsia_platform_identity_configuration = "fuchsia_platform_identity_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_product_configuration.bzl",
- _BUILD_TYPES = "BUILD_TYPES",
- _fuchsia_product_configuration = "fuchsia_product_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_platform_diagnostics_configuration.bzl",
- _ARCHIVIST_TYPES = "ARCHIVIST_TYPES",
- _fuchsia_platform_diagnostics_configuration = "fuchsia_platform_diagnostics_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_board_configuration.bzl",
- _fuchsia_board_configuration = "fuchsia_board_configuration",
-)
-load(
- "//fuchsia/private/assembly:providers.bzl",
- _FuchsiaProductAssemblyBundleInfo = "FuchsiaProductAssemblyBundleInfo",
- _FuchsiaProductImageInfo = "FuchsiaProductImageInfo",
- _FuchsiaScrutinyConfigInfo = "FuchsiaScrutinyConfigInfo",
-)
-load(
- "//fuchsia/private/assembly:assembly_bundle.bzl",
- _assembly_bundle = "assembly_bundle",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_partitions_configuration.bzl",
- _fuchsia_partitions_configuration = "fuchsia_partitions_configuration",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_product_bundle.bzl",
- _fuchsia_product_bundle = "fuchsia_product_bundle",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_zbi.bzl",
- _ZBI_COMPRESSION = "ZBI_COMPRESSION",
- _fuchsia_zbi = "fuchsia_zbi",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_vbmeta.bzl",
- _fuchsia_vbmeta = "fuchsia_vbmeta",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_filesystem_blobfs.bzl",
- _BLOBFS_LAYOUT = "BLOBFS_LAYOUT",
- _fuchsia_filesystem_blobfs = "fuchsia_filesystem_blobfs",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_filesystem_empty_account.bzl",
- _fuchsia_filesystem_empty_account = "fuchsia_filesystem_empty_account",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_filesystem_minfs.bzl",
- _fuchsia_filesystem_minfs = "fuchsia_filesystem_minfs",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_filesystem_empty_data.bzl",
- _fuchsia_filesystem_empty_data = "fuchsia_filesystem_empty_data",
- _fuchsia_filesystem_empty_minfs = "fuchsia_filesystem_empty_minfs",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_filesystem_reserved.bzl",
- _fuchsia_filesystem_reserved = "fuchsia_filesystem_reserved",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_fvm_nand.bzl",
- _fuchsia_fvm_nand = "fuchsia_fvm_nand",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_fvm_sparse.bzl",
- _fuchsia_fvm_sparse = "fuchsia_fvm_sparse",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_fvm_standard.bzl",
- _fuchsia_fvm_standard = "fuchsia_fvm_standard",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_bootstrap_partition.bzl",
- _fuchsia_bootstrap_partition = "fuchsia_bootstrap_partition",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_bootloader_partition.bzl",
- _fuchsia_bootloader_partition = "fuchsia_bootloader_partition",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_partition.bzl",
- _PARTITION_TYPE = "PARTITION_TYPE",
- _SLOT = "SLOT",
- _fuchsia_partition = "fuchsia_partition",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_scrutiny_config.bzl",
- _fuchsia_scrutiny_config = "fuchsia_scrutiny_config",
-)
-load(
- "//fuchsia/private/assembly:fuchsia_product_size_check.bzl",
- _fuchsia_product_size_check = "fuchsia_product_size_check",
-)
-load(
- "//fuchsia/private/workflows:fuchsia_task_flash.bzl",
- _fuchsia_task_flash = "fuchsia_task_flash",
-)
-
-# Rules
-assembly_bundle = _assembly_bundle
-fuchsia_prebuilt_package = _fuchsia_prebuilt_package
-fuchsia_assemble_package = _fuchsia_assemble_package
-fuchsia_images_configuration = _fuchsia_images_configuration
-fuchsia_platform_input_configuration = _fuchsia_platform_input_configuration
-fuchsia_platform_identity_configuration = _fuchsia_platform_identity_configuration
-fuchsia_platform_connectivity_configuration = _fuchsia_platform_connectivity_configuration
-fuchsia_platform_connectivity_wlan_configuration = _fuchsia_platform_connectivity_wlan_configuration
-fuchsia_platform_diagnostics_configuration = _fuchsia_platform_diagnostics_configuration
-fuchsia_platform_development_support_configuration = _fuchsia_platform_development_support_configuration
-fuchsia_platform_starnix_configuration = _fuchsia_platform_starnix_configuration
-fuchsia_product_configuration = _fuchsia_product_configuration
-fuchsia_board_configuration = _fuchsia_board_configuration
-fuchsia_product_image = _fuchsia_product_image
-fuchsia_partitions_configuration = _fuchsia_partitions_configuration
-fuchsia_product_bundle = _fuchsia_product_bundle
-fuchsia_product_size_check = _fuchsia_product_size_check
-fuchsia_task_flash = _fuchsia_task_flash
-fuchsia_zbi = _fuchsia_zbi
-fuchsia_vbmeta = _fuchsia_vbmeta
-fuchsia_filesystem_blobfs = _fuchsia_filesystem_blobfs
-fuchsia_filesystem_empty_account = _fuchsia_filesystem_empty_account
-fuchsia_filesystem_minfs = _fuchsia_filesystem_minfs
-fuchsia_filesystem_empty_data = _fuchsia_filesystem_empty_data
-
-# TODO(fxbug.dev/85134): Remove when in-tree Bazel configuration is updated to
-# use `fuchsia_filesystem_empty_data`.
-fuchsia_filesystem_empty_minfs = _fuchsia_filesystem_empty_minfs
-fuchsia_filesystem_reserved = _fuchsia_filesystem_reserved
-fuchsia_fvm_nand = _fuchsia_fvm_nand
-fuchsia_fvm_sparse = _fuchsia_fvm_sparse
-fuchsia_fvm_standard = _fuchsia_fvm_standard
-fuchsia_scrutiny_config = _fuchsia_scrutiny_config
-
-fuchsia_bootstrap_partition = _fuchsia_bootstrap_partition
-fuchsia_bootloader_partition = _fuchsia_bootloader_partition
-fuchsia_partition = _fuchsia_partition
-
-# Providers
-FuchsiaProductImageInfo = _FuchsiaProductImageInfo
-FuchsiaProductAssemblyBundleInfo = _FuchsiaProductAssemblyBundleInfo
-FuchsiaScrutinyConfigInfo = _FuchsiaScrutinyConfigInfo
-
-# constants
-BUILD_TYPES = _BUILD_TYPES
-ARCHIVIST_TYPES = _ARCHIVIST_TYPES
-INPUT_DEVICE_TYPE = _INPUT_DEVICE_TYPE
-FEATURE_CONTROL = _FEATURE_CONTROL
-ZBI_COMPRESSION = _ZBI_COMPRESSION
-BLOBFS_LAYOUT = _BLOBFS_LAYOUT
-PARTITION_TYPE = _PARTITION_TYPE
-SLOT = _SLOT
diff --git a/bazel_rules_fuchsia/fuchsia/constraints/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/constraints/BUILD.bazel
deleted file mode 100644
index 0de584f..0000000
--- a/bazel_rules_fuchsia/fuchsia/constraints/BUILD.bazel
+++ /dev/null
@@ -1,56 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Constraints and platforms for Fuchsia.
-
-load("@bazel_skylib//lib:selects.bzl", "selects")
-
-# The version of the Fuchsia toolchain. Specific to particular local builds of
-# Fuchsia or particular versions of the IDK.
-constraint_setting(
- name = "version",
- visibility = ["//visibility:public"],
-)
-
-# CPU based configurations
-
-selects.config_setting_group(
- name = "cpu_arm64",
- match_any = [
- ":cpu_arm64_flag",
- ":cpu_arm64_platform",
- ],
-)
-
-selects.config_setting_group(
- name = "cpu_x64",
- match_any = [
- ":cpu_x64_flag",
- ":cpu_x64_platform",
- ],
-)
-
-config_setting(
- name = "cpu_arm64_flag",
- values = {"cpu": "aarch64"},
-)
-
-config_setting(
- name = "cpu_x64_flag",
- values = {"cpu": "x64"},
-)
-
-config_setting(
- name = "cpu_arm64_platform",
- constraint_values = [
- "@platforms//cpu:aarch64",
- ],
-)
-
-config_setting(
- name = "cpu_x64_platform",
- constraint_values = [
- "@platforms//cpu:x86_64",
- ],
-)
diff --git a/bazel_rules_fuchsia/fuchsia/constraints/os/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/constraints/os/BUILD.bazel
deleted file mode 100644
index 5b87b7f..0000000
--- a/bazel_rules_fuchsia/fuchsia/constraints/os/BUILD.bazel
+++ /dev/null
@@ -1,11 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# TODO(jayzhuang): Remove this file when downstream usages are removed.
-
-alias(
- name = "fuchsia",
- actual = "@platforms//os:fuchsia",
- visibility = ["//visibility:public"],
-)
diff --git a/bazel_rules_fuchsia/fuchsia/constraints/platforms/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/constraints/platforms/BUILD.bazel
deleted file mode 100644
index a8bcf1b..0000000
--- a/bazel_rules_fuchsia/fuchsia/constraints/platforms/BUILD.bazel
+++ /dev/null
@@ -1,23 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Platform definitions for Fuchsia.
-
-platform(
- name = "fuchsia_x64",
- constraint_values = [
- "@platforms//cpu:x86_64",
- "@platforms//os:fuchsia",
- ],
- visibility = ["//visibility:public"],
-)
-
-platform(
- name = "fuchsia_arm64",
- constraint_values = [
- "@platforms//cpu:aarch64",
- "@platforms//os:fuchsia",
- ],
- visibility = ["//visibility:public"],
-)
diff --git a/bazel_rules_fuchsia/fuchsia/defs.bzl b/bazel_rules_fuchsia/fuchsia/defs.bzl
deleted file mode 100644
index 73b2746..0000000
--- a/bazel_rules_fuchsia/fuchsia/defs.bzl
+++ /dev/null
@@ -1,149 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Public definitions for Fuchsia rules.
-
-Documentation for all rules exported by this file is located at docs/defs.md"""
-
-load(
- "//fuchsia/private:fuchsia_bind_library.bzl",
- _fuchsia_bind_library = "fuchsia_bind_library",
-)
-load(
- "//fuchsia/private:fuchsia_cc.bzl",
- _fuchsia_cc_binary = "fuchsia_cc_binary",
- _fuchsia_cc_test = "fuchsia_cc_test",
- _fuchsia_wrap_cc_binary = "fuchsia_wrap_cc_binary",
- _fuchsia_wrap_cc_test = "fuchsia_wrap_cc_test",
-)
-load(
- "//fuchsia/private:fuchsia_component.bzl",
- _fuchsia_component = "fuchsia_component",
- _fuchsia_driver_component = "fuchsia_driver_component",
- _fuchsia_test_component = "fuchsia_test_component",
-)
-load(
- "//fuchsia/private:fuchsia_component_manifest.bzl",
- _fuchsia_component_manifest = "fuchsia_component_manifest",
- _fuchsia_component_manifest_shard = "fuchsia_component_manifest_shard",
-)
-load(
- "//fuchsia/private:fuchsia_fidl_library.bzl",
- _fuchsia_fidl_library = "fuchsia_fidl_library",
-)
-load(
- "//fuchsia/private:fuchsia_fidl_bind_library.bzl",
- _fuchsia_fidl_bind_library = "fuchsia_fidl_bind_library",
-)
-load(
- "//fuchsia/private:fuchsia_bind_cc_library.bzl",
- _fuchsia_bind_cc_library = "fuchsia_bind_cc_library",
-)
-load(
- "//fuchsia/private:legacy_fuchsia_fidl_cc_library.bzl",
- _fuchsia_fidl_hlcpp_library = "fuchsia_fidl_hlcpp_library",
- _fuchsia_fidl_llcpp_library = "fuchsia_fidl_llcpp_library",
-)
-load(
- "//fuchsia/private:fuchsia_driver_bind_rules.bzl",
- _fuchsia_driver_bind_bytecode = "fuchsia_driver_bind_bytecode",
- _fuchsia_driver_bind_header = "fuchsia_driver_bind_header",
-)
-load(
- "//fuchsia/private:fuchsia_debug_symbols.bzl",
- _fuchsia_debug_symbols = "fuchsia_debug_symbols",
-)
-load(
- "//fuchsia/private:fuchsia_driver_tool.bzl",
- _fuchsia_driver_tool = "fuchsia_driver_tool",
-)
-load(
- "//fuchsia/private:fuchsia_package.bzl",
- _fuchsia_package = "fuchsia_package",
- _fuchsia_test_package = "fuchsia_test_package",
- _fuchsia_unittest_package = "fuchsia_unittest_package",
-)
-load(
- "//fuchsia/private:fuchsia_rust.bzl",
- _fuchsia_wrap_rust_binary = "fuchsia_wrap_rust_binary",
-)
-load(
- "//fuchsia/private:fuchsia_package_resource.bzl",
- _fuchsia_package_resource = "fuchsia_package_resource",
- _fuchsia_package_resource_group = "fuchsia_package_resource_group",
-)
-load(
- "//fuchsia/private:fuchsia_package_repository.bzl",
- _fuchsia_package_repository = "fuchsia_package_repository",
-)
-load(
- "//fuchsia/private:fuchsia_local_package_repository.bzl",
- _fuchsia_local_package_repository = "fuchsia_local_package_repository",
-)
-load(
- "//fuchsia/private:fuchsia_package_group.bzl",
- _fuchsia_package_group = "fuchsia_package_group",
-)
-load(
- "//fuchsia/private:fuchsia_select.bzl",
- _fuchsia_only_target = "fuchsia_only_target",
- _fuchsia_select = "fuchsia_select",
- _if_fuchsia = "if_fuchsia",
-)
-load(
- "//fuchsia/private:compilation_database.bzl",
- _clangd_compilation_database = "clangd_compilation_database",
-)
-load(
- "@rules_fuchsia//fuchsia/private:fuchsia_emulator.bzl",
- _fuchsia_emulator = "fuchsia_emulator",
-)
-load(
- "@rules_fuchsia//fuchsia/private:fuchsia_remote_product_bundle.bzl",
- _fuchsia_remote_product_bundle = "fuchsia_remote_product_bundle",
-)
-
-# Workspace-dependent rules.
-load(
- "//fuchsia/workspace:fuchsia_toolchain_info.bzl",
- _fuchsia_toolchain_info = "fuchsia_toolchain_info",
-)
-
-# Rules
-
-fuchsia_bind_library = _fuchsia_bind_library
-fuchsia_cc_binary = _fuchsia_cc_binary
-fuchsia_cc_test = _fuchsia_cc_test
-fuchsia_wrap_cc_binary = _fuchsia_wrap_cc_binary
-fuchsia_wrap_cc_test = _fuchsia_wrap_cc_test
-fuchsia_wrap_rust_binary = _fuchsia_wrap_rust_binary
-fuchsia_component = _fuchsia_component
-fuchsia_test_component = _fuchsia_test_component
-fuchsia_component_manifest = _fuchsia_component_manifest
-fuchsia_component_manifest_shard = _fuchsia_component_manifest_shard
-fuchsia_debug_symbols = _fuchsia_debug_symbols
-fuchsia_driver_component = _fuchsia_driver_component
-fuchsia_driver_bind_bytecode = _fuchsia_driver_bind_bytecode
-fuchsia_driver_bind_header = _fuchsia_driver_bind_header
-fuchsia_driver_tool = _fuchsia_driver_tool
-fuchsia_emulator = _fuchsia_emulator
-fuchsia_fidl_library = _fuchsia_fidl_library
-fuchsia_fidl_bind_library = _fuchsia_fidl_bind_library
-fuchsia_bind_cc_library = _fuchsia_bind_cc_library
-fuchsia_fidl_hlcpp_library = _fuchsia_fidl_hlcpp_library
-fuchsia_fidl_llcpp_library = _fuchsia_fidl_llcpp_library
-fuchsia_package = _fuchsia_package
-fuchsia_test_package = _fuchsia_test_package
-fuchsia_unittest_package = _fuchsia_unittest_package
-fuchsia_package_resource = _fuchsia_package_resource
-fuchsia_package_resource_group = _fuchsia_package_resource_group
-fuchsia_package_repository = _fuchsia_package_repository
-fuchsia_local_package_repository = _fuchsia_local_package_repository
-fuchsia_package_group = _fuchsia_package_group
-fuchsia_remote_product_bundle = _fuchsia_remote_product_bundle
-fuchsia_select = _fuchsia_select
-if_fuchsia = _if_fuchsia
-fuchsia_only_target = _fuchsia_only_target
-clangd_compilation_database = _clangd_compilation_database
-fuchsia_toolchain_info = _fuchsia_toolchain_info
diff --git a/bazel_rules_fuchsia/fuchsia/deps.bzl b/bazel_rules_fuchsia/fuchsia/deps.bzl
deleted file mode 100644
index 8d8ca4d..0000000
--- a/bazel_rules_fuchsia/fuchsia/deps.bzl
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Defines rules for use in WORKSPACE files."""
-
-load(
- "//fuchsia/workspace:fuchsia_clang_repository.bzl",
- _fuchsia_clang_ext = "fuchsia_clang_ext",
- _fuchsia_clang_repository = "fuchsia_clang_repository",
-)
-load(
- "//fuchsia/workspace:fuchsia_sdk_repository.bzl",
- _fuchsia_sdk_ext = "fuchsia_sdk_ext",
- _fuchsia_sdk_repository = "fuchsia_sdk_repository",
-)
-load(
- "//fuchsia/workspace:rules_fuchsia_deps.bzl",
- _rules_fuchsia_deps = "rules_fuchsia_deps",
-)
-load(
- "//fuchsia/workspace:python_runtime_repository.bzl",
- _python_runtime_repository = "python_runtime_repository",
-)
-
-# See corresponding `.bzl` files in fuchsia/private for documentation.
-fuchsia_clang_repository = _fuchsia_clang_repository
-fuchsia_clang_ext = _fuchsia_clang_ext
-fuchsia_sdk_repository = _fuchsia_sdk_repository
-fuchsia_sdk_ext = _fuchsia_sdk_ext
-rules_fuchsia_deps = _rules_fuchsia_deps
-python_runtime_repository = _python_runtime_repository
diff --git a/bazel_rules_fuchsia/fuchsia/licenses.bzl b/bazel_rules_fuchsia/fuchsia/licenses.bzl
deleted file mode 100644
index 0178245..0000000
--- a/bazel_rules_fuchsia/fuchsia/licenses.bzl
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Public definitions for licenses related rules."""
-
-load(
- "//fuchsia/private/licenses:fuchsia_licenses_classification.bzl",
- _fuchsia_licenses_classification = "fuchsia_licenses_classification",
-)
-load(
- "//fuchsia/private/licenses:fuchsia_licenses_notice.bzl",
- _fuchsia_licenses_notice = "fuchsia_licenses_notice",
-)
-load(
- "//fuchsia/private/licenses:fuchsia_licenses_review.bzl",
- _fuchsia_licenses_review = "fuchsia_licenses_review",
-)
-load(
- "//fuchsia/private/licenses:fuchsia_licenses_spdx.bzl",
- _fuchsia_licenses_spdx = "fuchsia_licenses_spdx",
-)
-
-fuchsia_licenses_classification = _fuchsia_licenses_classification
-fuchsia_licenses_notice = _fuchsia_licenses_notice
-fuchsia_licenses_review = _fuchsia_licenses_review
-fuchsia_licenses_spdx = _fuchsia_licenses_spdx
diff --git a/bazel_rules_fuchsia/fuchsia/manifests/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/manifests/BUILD.bazel
deleted file mode 100644
index 95fabcc..0000000
--- a/bazel_rules_fuchsia/fuchsia/manifests/BUILD.bazel
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-exports_files(
- glob([
- "*.ensure",
- "*.resolved",
- ]),
-)
diff --git a/bazel_rules_fuchsia/fuchsia/manifests/clang.ensure b/bazel_rules_fuchsia/fuchsia/manifests/clang.ensure
deleted file mode 100644
index 24768c0..0000000
--- a/bazel_rules_fuchsia/fuchsia/manifests/clang.ensure
+++ /dev/null
@@ -1,4 +0,0 @@
-$ResolvedVersions clang.resolved
-$VerifiedPlatform linux-amd64 linux-arm64 mac-amd64 windows-amd64
-fuchsia/third_party/clang/${os=linux}-${arch} git_revision:20d06c833d833ef6b2d0f519cc4a7998d49a2803
-fuchsia/third_party/clang/${os=mac,windows}-amd64 git_revision:20d06c833d833ef6b2d0f519cc4a7998d49a2803
diff --git a/bazel_rules_fuchsia/fuchsia/manifests/clang.resolved b/bazel_rules_fuchsia/fuchsia/manifests/clang.resolved
deleted file mode 100644
index 3b62c39..0000000
--- a/bazel_rules_fuchsia/fuchsia/manifests/clang.resolved
+++ /dev/null
@@ -1,18 +0,0 @@
-# This file is auto-generated by 'cipd ensure-file-resolve'.
-# Do not modify manually. All changes will be overwritten.
-
-fuchsia/third_party/clang/linux-amd64
- git_revision:20d06c833d833ef6b2d0f519cc4a7998d49a2803
- D6iCh3JujnaDChg_h334WzcS5ozkqQtyMo9OtNb9TmQC
-
-fuchsia/third_party/clang/linux-arm64
- git_revision:20d06c833d833ef6b2d0f519cc4a7998d49a2803
- 7Rx4R-lmtKYg2mp--cCM9_ADSKbuWpgPeFM5alVo8hwC
-
-fuchsia/third_party/clang/mac-amd64
- git_revision:20d06c833d833ef6b2d0f519cc4a7998d49a2803
- dvjuHpfz5ool4LLND1h-AT8iHs6Wj3nk2T7ZlxuXK78C
-
-fuchsia/third_party/clang/windows-amd64
- git_revision:20d06c833d833ef6b2d0f519cc4a7998d49a2803
- OnEbyJg8zm_bAtnws9jZ6Jov0RDArEHJvb8FioRiQCIC
diff --git a/bazel_rules_fuchsia/fuchsia/manifests/core_experimental_sdk.ensure b/bazel_rules_fuchsia/fuchsia/manifests/core_experimental_sdk.ensure
deleted file mode 100644
index f9ef0d2..0000000
--- a/bazel_rules_fuchsia/fuchsia/manifests/core_experimental_sdk.ensure
+++ /dev/null
@@ -1,5 +0,0 @@
-$ResolvedVersions core_experimental_sdk.resolved
-$VerifiedPlatform linux-amd64 mac-amd64
-fuchsia/sdk/experimental/${os=linux}-${arch} version:11.20230126.1.1
-fuchsia/sdk/experimental/${os=mac}-amd64 version:11.20230126.1.1
-
diff --git a/bazel_rules_fuchsia/fuchsia/manifests/core_experimental_sdk.resolved b/bazel_rules_fuchsia/fuchsia/manifests/core_experimental_sdk.resolved
deleted file mode 100644
index 6d8af1f..0000000
--- a/bazel_rules_fuchsia/fuchsia/manifests/core_experimental_sdk.resolved
+++ /dev/null
@@ -1,10 +0,0 @@
-# This file is auto-generated by 'cipd ensure-file-resolve'.
-# Do not modify manually. All changes will be overwritten.
-
-fuchsia/sdk/experimental/linux-amd64
- version:11.20230126.1.1
- utXafvzobKrQIlyMGaaMeI1g_gdAL4ics7dTWKkboFAC
-
-fuchsia/sdk/experimental/mac-amd64
- version:11.20230126.1.1
- 3fOQvAijLGUId90Vs6LIIpkUAorg0chT3KhVSJ3zK-MC
diff --git a/bazel_rules_fuchsia/fuchsia/manifests/core_sdk.ensure b/bazel_rules_fuchsia/fuchsia/manifests/core_sdk.ensure
deleted file mode 100644
index 5d82e97..0000000
--- a/bazel_rules_fuchsia/fuchsia/manifests/core_sdk.ensure
+++ /dev/null
@@ -1,5 +0,0 @@
-$ResolvedVersions core_sdk.resolved
-$VerifiedPlatform linux-amd64 mac-amd64
-fuchsia/sdk/core/${os=linux}-${arch} version:11.20230126.1.1
-fuchsia/sdk/core/${os=mac}-amd64 version:11.20230126.1.1
-
diff --git a/bazel_rules_fuchsia/fuchsia/manifests/core_sdk.resolved b/bazel_rules_fuchsia/fuchsia/manifests/core_sdk.resolved
deleted file mode 100644
index c7cd33a..0000000
--- a/bazel_rules_fuchsia/fuchsia/manifests/core_sdk.resolved
+++ /dev/null
@@ -1,10 +0,0 @@
-# This file is auto-generated by 'cipd ensure-file-resolve'.
-# Do not modify manually. All changes will be overwritten.
-
-fuchsia/sdk/core/linux-amd64
- version:11.20230126.1.1
- kdjOCYzDtnfY30985MNdo1wYARRjcclJKGrL3RyQ5sIC
-
-fuchsia/sdk/core/mac-amd64
- version:11.20230126.1.1
- MyL3JcOBni9CTx9wzQTu_5N-tYH3GfFhG4ByIVH9OmUC
diff --git a/bazel_rules_fuchsia/fuchsia/manifests/python.ensure b/bazel_rules_fuchsia/fuchsia/manifests/python.ensure
deleted file mode 100644
index d04fd37..0000000
--- a/bazel_rules_fuchsia/fuchsia/manifests/python.ensure
+++ /dev/null
@@ -1,3 +0,0 @@
-$ResolvedVersions python.resolved
-$VerifiedPlatform linux-amd64 linux-arm64 mac-amd64 mac-arm64
-infra/3pp/tools/cpython3/${platform} version:2@3.11.1.chromium.23
\ No newline at end of file
diff --git a/bazel_rules_fuchsia/fuchsia/manifests/python.resolved b/bazel_rules_fuchsia/fuchsia/manifests/python.resolved
deleted file mode 100644
index dcba7eb..0000000
--- a/bazel_rules_fuchsia/fuchsia/manifests/python.resolved
+++ /dev/null
@@ -1,18 +0,0 @@
-# This file is auto-generated by 'cipd ensure-file-resolve'.
-# Do not modify manually. All changes will be overwritten.
-
-infra/3pp/tools/cpython3/linux-amd64
- version:2@3.11.1.chromium.23
- Lz4altWz5EQXTrQsoTtixoeXdir8WdzRxCJ0o5EFjNgC
-
-infra/3pp/tools/cpython3/linux-arm64
- version:2@3.11.1.chromium.23
- t2-3s0AxWgvNSrK77JvqBBPS3zScUBLJOuBhrh5NuusC
-
-infra/3pp/tools/cpython3/mac-amd64
- version:2@3.11.1.chromium.23
- LSmqt4AlcTBlaTQFVKAVTWF6ipHlMt5-lSDL-UErNaAC
-
-infra/3pp/tools/cpython3/mac-arm64
- version:2@3.11.1.chromium.23
- 3ujGuL2sZVvV3sH5Kx4eq1vUzunQmXT-qxWDeCUDYYoC
diff --git a/bazel_rules_fuchsia/fuchsia/private/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/private/BUILD.bazel
deleted file mode 100644
index cf4c02f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/BUILD.bazel
+++ /dev/null
@@ -1,23 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-exports_files(
- glob([
- "*.bzl",
- ]),
- visibility = ["//:__subpackages__"],
-)
-
-exports_files(
- glob([
- "templates/*",
- ]),
- visibility = ["//visibility:public"],
-)
-
-filegroup(
- name = "all_starlark_files",
- srcs = glob(["*.bzl"]),
- visibility = ["//:__subpackages__"],
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/private/assembly/BUILD.bazel
deleted file mode 100644
index b175093..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/BUILD.bazel
+++ /dev/null
@@ -1,16 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-exports_files(
- glob([
- "*.bzl",
- ]),
- visibility = ["//:__subpackages__"],
-)
-
-filegroup(
- name = "all_starlark_files",
- srcs = glob(["*.bzl"]),
- visibility = ["//:__subpackages__"],
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/assembly_bundle.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/assembly_bundle.bzl
deleted file mode 100644
index fd59bac..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/assembly_bundle.bzl
+++ /dev/null
@@ -1,30 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Private rule used by fuchsia_product_assembly_bundle."""
-
-load(":providers.bzl", "FuchsiaProductAssemblyBundleInfo")
-
-def _assembly_bundle_impl(ctx):
- return [FuchsiaProductAssemblyBundleInfo(
- dir = ctx.file.dir,
- files = ctx.files.files,
- )]
-
-assembly_bundle = rule(
- implementation = _assembly_bundle_impl,
- provides = [FuchsiaProductAssemblyBundleInfo],
- attrs = {
- "dir": attr.label(
- doc = "path to the assembly bundle directory",
- mandatory = True,
- allow_single_file = True,
- ),
- "files": attr.label(
- doc = "a list of all files to include in the assembly bundle",
- mandatory = True,
- allow_files = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_assemble_package.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_assemble_package.bzl
deleted file mode 100644
index 594bd20..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_assemble_package.bzl
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load("//fuchsia/private:providers.bzl", "FuchsiaPackageInfo")
-load(":providers.bzl", "FuchsiaAssembledPackageInfo", "FuchsiaConfigData")
-
-def _fuchsia_assemble_package_impl(ctx):
- configs = []
- deps = []
- for config_file in ctx.attr.configs:
- f = config_file.files.to_list()[0]
- configs.append(FuchsiaConfigData(
- source = f,
- destination = ctx.attr.configs[config_file],
- ))
- deps.append(f)
- package = ctx.attr.package[FuchsiaPackageInfo]
- deps.append(package.package_manifest)
-
- return [
- DefaultInfo(files = depset(deps)),
- FuchsiaAssembledPackageInfo(
- package = package,
- configs = configs,
- ),
- ]
-
-fuchsia_assemble_package = rule(
- doc = """Generates assembled config based on package and their config.""",
- implementation = _fuchsia_assemble_package_impl,
- provides = [FuchsiaAssembledPackageInfo],
- attrs = {
- "package": attr.label(
- providers = [FuchsiaPackageInfo],
- mandatory = True,
- ),
- "configs": attr.label_keyed_string_dict(
- doc = "Config-datas that are attached to the package. It's a dictionary of source files to destination string",
- allow_files = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_board_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_board_configuration.bzl
deleted file mode 100644
index 9bd5edc..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_board_configuration.bzl
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright 2023 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- ":providers.bzl",
- "FuchsiaBoardConfigInfo",
-)
-
-def _fuchsia_board_configuration_impl(ctx):
- board_config = {}
- board_config["name"] = ctx.attr.board_name
- board_config["provided_features"] = ctx.attr.provided_features
-
- board_config_file = ctx.actions.declare_file(ctx.label.name + "_board_config.json")
- content = json.encode_indent(board_config, indent = " ")
- ctx.actions.write(board_config_file, content)
-
- return [
- DefaultInfo(
- files = depset(
- direct = [board_config_file],
- ),
- ),
- FuchsiaBoardConfigInfo(
- board_config = board_config_file,
- ),
- ]
-
-fuchsia_board_configuration = rule(
- doc = """Generates a board configuration file.""",
- implementation = _fuchsia_board_configuration_impl,
- attrs = {
- "board_name": attr.string(
- doc = "Name of this board.",
- mandatory = True,
- ),
- "provided_features": attr.string_list(
- doc = "The features that this board provides to the product.",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_bootloader_partition.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_bootloader_partition.bzl
deleted file mode 100644
index 7dd6f42..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_bootloader_partition.bzl
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- ":providers.bzl",
- "FuchsiaPartitionInfo",
-)
-
-def _fuchsia_bootloader_partition_impl(ctx):
- bootloader_partition = {
- "name": ctx.attr.partition_name,
- "image": ctx.file.image.path,
- "type": ctx.attr.type,
- }
-
- return [
- DefaultInfo(files = depset(direct = [ctx.file.image])),
- FuchsiaPartitionInfo(
- partition = bootloader_partition,
- ),
- ]
-
-fuchsia_bootloader_partition = rule(
- doc = """Define a partition mapping from partition to image.""",
- implementation = _fuchsia_bootloader_partition_impl,
- provides = [FuchsiaPartitionInfo],
- attrs = {
- "partition_name": attr.string(
- doc = "Name of the partition",
- mandatory = True,
- ),
- "image": attr.label(
- doc = "The bootloader image file",
- allow_single_file = True,
- mandatory = True,
- ),
- "type": attr.string(
- doc = "The firmware type provided to the update system",
- mandatory = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_bootstrap_partition.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_bootstrap_partition.bzl
deleted file mode 100644
index 78684ea..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_bootstrap_partition.bzl
+++ /dev/null
@@ -1,49 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- ":providers.bzl",
- "FuchsiaPartitionInfo",
-)
-
-def _fuchsia_bootstrap_partition_impl(ctx):
- bootstrap_partition = {
- "name": ctx.attr.partition_name,
- "image": ctx.file.image.path,
- }
- if ctx.attr.condition_variable != "":
- bootstrap_partition["condition"] = {
- "variable": ctx.attr.condition_variable,
- "value": ctx.attr.condition_value,
- }
-
- return [
- DefaultInfo(files = depset(direct = [ctx.file.image])),
- FuchsiaPartitionInfo(
- partition = bootstrap_partition,
- ),
- ]
-
-fuchsia_bootstrap_partition = rule(
- doc = """Define a partition mapping from partition to image.""",
- implementation = _fuchsia_bootstrap_partition_impl,
- provides = [FuchsiaPartitionInfo],
- attrs = {
- "partition_name": attr.string(
- doc = "Name of the partition",
- mandatory = True,
- ),
- "image": attr.label(
- doc = "The bootstrap image file",
- allow_single_file = True,
- mandatory = True,
- ),
- "condition_variable": attr.string(
- doc = "Condition that needs to be met before flash.",
- ),
- "condition_value": attr.string(
- doc = "Condition that needs to be met before flash.",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_blobfs.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_blobfs.bzl
deleted file mode 100644
index cba4d91..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_blobfs.bzl
+++ /dev/null
@@ -1,67 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaFsBlobFsInfo")
-
-# Define Blob FS Layout
-BLOBFS_LAYOUT = struct(
- COMPACT = "compact",
- DEPRECATED_PADDED = "deprecated_padded",
-)
-
-def _fuchsia_filesystem_blobfs_impl(ctx):
- blobfs_info = {
- "name": ctx.attr.blobfs_name,
- "compress": ctx.attr.compress,
- "layout": ctx.attr.layout,
- "type": "blobfs",
- }
- if ctx.attr.maximum_bytes:
- blobfs_info["maximum_bytes"] = int(ctx.attr.maximum_bytes)
- if ctx.attr.minimum_data_bytes:
- blobfs_info["minimum_data_bytes"] = int(ctx.attr.minimum_data_bytes)
- if ctx.attr.maximum_contents_size:
- blobfs_info["maximum_contents_size"] = int(ctx.attr.maximum_contents_size)
- if ctx.attr.minimum_inodes:
- blobfs_info["minimum_inodes"] = int(ctx.attr.minimum_inodes)
-
- return [
- FuchsiaFsBlobFsInfo(
- blobfs_name = ctx.attr.blobfs_name,
- blobfs_info = blobfs_info,
- ),
- ]
-
-fuchsia_filesystem_blobfs = rule(
- doc = """Generates a blobfs filesystem.""",
- implementation = _fuchsia_filesystem_blobfs_impl,
- provides = [FuchsiaFsBlobFsInfo],
- attrs = {
- "blobfs_name": attr.string(
- doc = "Name of filesystem",
- default = "blob",
- ),
- "compress": attr.bool(
- doc = "Whether to compress the volume file.",
- default = True,
- ),
- "layout": attr.string(
- default = BLOBFS_LAYOUT.COMPACT,
- values = [BLOBFS_LAYOUT.COMPACT, BLOBFS_LAYOUT.DEPRECATED_PADDED],
- ),
- "maximum_bytes": attr.string(
- doc = "Reserve |minimum_data_bytes| and |minimum_inodes| in the FVM, and ensure" +
- "that the final reserved size does not exceed |maximum_bytes|.",
- ),
- "minimum_data_bytes": attr.string(
- doc = "Reserve space for at least this many data bytes.",
- ),
- "minimum_inodes": attr.string(
- doc = "Reserved space for this many inodes.",
- ),
- "maximum_contents_size": attr.string(
- doc = "Maximum amount of contents for an assembled blobfs.",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_empty_account.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_empty_account.bzl
deleted file mode 100644
index 74612b0..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_empty_account.bzl
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaFsEmptyAccountInfo")
-
-def _fuchsia_filesystem_empty_account_impl(ctx):
- return [
- FuchsiaFsEmptyAccountInfo(
- empty_account_name = ctx.attr.empty_account_name,
- ),
- ]
-
-fuchsia_filesystem_empty_account = rule(
- doc = """Generates an empty account filesystem.""",
- implementation = _fuchsia_filesystem_empty_account_impl,
- provides = [FuchsiaFsEmptyAccountInfo],
- attrs = {
- "empty_account_name": attr.string(
- doc = "Name of filesystem",
- default = "account",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_empty_data.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_empty_data.bzl
deleted file mode 100644
index f5fc456..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_empty_data.bzl
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaFsEmptyDataInfo")
-
-def _fuchsia_filesystem_empty_data_impl(ctx):
- return [
- FuchsiaFsEmptyDataInfo(
- empty_data_name = ctx.attr.empty_data_name,
- ),
- ]
-
-fuchsia_filesystem_empty_data = rule(
- doc = """Generates an empty data filesystem.""",
- implementation = _fuchsia_filesystem_empty_data_impl,
- provides = [FuchsiaFsEmptyDataInfo],
- attrs = {
- "empty_data_name": attr.string(
- doc = "Name of filesystem",
- default = "empty_data",
- ),
- },
-)
-
-def _fuchsia_filesystem_empty_minfs_impl(ctx):
- return [
- FuchsiaFsEmptyDataInfo(
- empty_data_name = ctx.attr.empty_minfs_name,
- ),
- ]
-
-fuchsia_filesystem_empty_minfs = rule(
- doc = """Generates an empty Minfs filesystem.""",
- implementation = _fuchsia_filesystem_empty_minfs_impl,
- provides = [FuchsiaFsEmptyDataInfo],
- attrs = {
- "empty_minfs_name": attr.string(
- doc = "Name of filesystem",
- default = "empty_data",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_minfs.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_minfs.bzl
deleted file mode 100644
index 8d59299..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_minfs.bzl
+++ /dev/null
@@ -1,45 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaFsMinFsInfo")
-
-def _fuchsia_filesystem_minfs_impl(ctx):
- minfs_info = {
- "type": "minfs",
- "name": ctx.attr.minfs_name,
- }
- if ctx.attr.maximum_bytes:
- minfs_info["maximum_bytes"] = int(ctx.attr.maximum_bytes)
- if ctx.attr.minimum_data_bytes:
- minfs_info["minimum_data_bytes"] = int(ctx.attr.minimum_data_bytes)
- if ctx.attr.minimum_inodes:
- minfs_info["maximum_contents_size"] = int(ctx.attr.minimum_inodes)
- return [
- FuchsiaFsMinFsInfo(
- minfs_name = ctx.attr.minfs_name,
- minfs_info = minfs_info,
- ),
- ]
-
-fuchsia_filesystem_minfs = rule(
- doc = """Generates a minfs filesystem.""",
- implementation = _fuchsia_filesystem_minfs_impl,
- provides = [FuchsiaFsMinFsInfo],
- attrs = {
- "minfs_name": attr.string(
- doc = "Name of filesystem",
- default = "data",
- ),
- "maximum_bytes": attr.string(
- doc = "Reserve |minimum_data_bytes| and |minimum_inodes| in the FVM, and ensure" +
- "that the final reserved size does not exceed |maximum_bytes|.",
- ),
- "minimum_data_bytes": attr.string(
- doc = "Reserve space for at least this many data bytes.",
- ),
- "minimum_inodes": attr.string(
- doc = "Reserved space for this many inodes.",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_reserved.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_reserved.bzl
deleted file mode 100644
index 9f4baf5..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_filesystem_reserved.bzl
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaFsReservedInfo")
-
-def _fuchsia_filesystem_reserved_impl(ctx):
- reserved_info = {
- "type": "reserved",
- "name": ctx.attr.reserved_name,
- }
- if ctx.attr.slices:
- reserved_info["slices"] = int(ctx.attr.slices)
- return [
- FuchsiaFsReservedInfo(
- reserved_name = ctx.attr.reserved_name,
- reserved_info = reserved_info,
- ),
- ]
-
-fuchsia_filesystem_reserved = rule(
- doc = """Generates a reserved filesystem.""",
- implementation = _fuchsia_filesystem_reserved_impl,
- provides = [FuchsiaFsReservedInfo],
- attrs = {
- "reserved_name": attr.string(
- doc = "Name of filesystem",
- default = "internal",
- ),
- "slices": attr.string(
- doc = "The number of slices to reserve.",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_fvm_nand.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_fvm_nand.bzl
deleted file mode 100644
index 37f1767..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_fvm_nand.bzl
+++ /dev/null
@@ -1,79 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- ":providers.bzl",
- "FuchsiaFVMNandInfo",
- "FuchsiaFsBlobFsInfo",
- "FuchsiaFsEmptyAccountInfo",
- "FuchsiaFsEmptyDataInfo",
- "FuchsiaFsMinFsInfo",
- "FuchsiaFsReservedInfo",
-)
-
-def _fuchsia_fvm_nand_impl(ctx):
- fvm_info = {
- "type": "nand",
- "name": ctx.attr.fvm_nand_name,
- }
- if ctx.attr.max_disk_size:
- fvm_info["max_disk_size"] = int(ctx.attr.max_disk_size)
- if ctx.attr.compress:
- fvm_info["compress"] = ctx.attr.compress
- if ctx.attr.block_count:
- fvm_info["block_count"] = int(ctx.attr.block_count)
- if ctx.attr.oob_size:
- fvm_info["oob_size"] = int(ctx.attr.oob_size)
- if ctx.attr.page_size:
- fvm_info["page_size"] = int(ctx.attr.page_size)
- if ctx.attr.pages_per_block:
- fvm_info["pages_per_block"] = int(ctx.attr.pages_per_block)
- return [
- FuchsiaFVMNandInfo(
- fvm_nand_name = ctx.attr.fvm_nand_name,
- filesystems = ctx.attr.filesystems,
- fvm_info = fvm_info,
- ),
- ]
-
-fuchsia_fvm_nand = rule(
- doc = """Generates a FVM prepared for a Nand partition.""",
- implementation = _fuchsia_fvm_nand_impl,
- provides = [FuchsiaFVMNandInfo],
- attrs = {
- "fvm_nand_name": attr.string(
- doc = "Name of fvm file",
- mandatory = True,
- ),
- "filesystems": attr.label_list(
- doc = "Filesystems to use",
- providers = [
- [FuchsiaFsBlobFsInfo],
- [FuchsiaFsMinFsInfo],
- [FuchsiaFsEmptyDataInfo],
- [FuchsiaFsEmptyAccountInfo],
- [FuchsiaFsReservedInfo],
- ],
- mandatory = True,
- ),
- "max_disk_size": attr.string(
- doc = "The maximum size the FVM can expand to at runtime.",
- ),
- "compress": attr.bool(
- doc = "Whether to compress the fvm file.",
- ),
- "block_count": attr.string(
- doc = "The number of blocks.",
- ),
- "oob_size": attr.string(
- doc = "The out of bound size.",
- ),
- "page_size": attr.string(
- doc = "Page size as perceived by the FTL.",
- ),
- "pages_per_block": attr.string(
- doc = "Number of pages per erase block unit.",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_fvm_sparse.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_fvm_sparse.bzl
deleted file mode 100644
index 9e93de2..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_fvm_sparse.bzl
+++ /dev/null
@@ -1,54 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- ":providers.bzl",
- "FuchsiaFVMSparseInfo",
- "FuchsiaFsBlobFsInfo",
- "FuchsiaFsEmptyAccountInfo",
- "FuchsiaFsEmptyDataInfo",
- "FuchsiaFsMinFsInfo",
- "FuchsiaFsReservedInfo",
-)
-
-def _fuchsia_fvm_sparse_impl(ctx):
- fvm_info = {
- "type": "sparse",
- "name": ctx.attr.fvm_sparse_name,
- }
- if ctx.attr.max_disk_size:
- fvm_info["max_disk_size"] = int(ctx.attr.max_disk_size)
- return [
- FuchsiaFVMSparseInfo(
- fvm_sparse_name = ctx.attr.fvm_sparse_name,
- filesystems = ctx.attr.filesystems,
- fvm_info = fvm_info,
- ),
- ]
-
-fuchsia_fvm_sparse = rule(
- doc = """Generates a fvm that is compressed sparse.""",
- implementation = _fuchsia_fvm_sparse_impl,
- provides = [FuchsiaFVMSparseInfo],
- attrs = {
- "fvm_sparse_name": attr.string(
- doc = "Name of fvm file",
- mandatory = True,
- ),
- "filesystems": attr.label_list(
- doc = "Filesystems to use",
- providers = [
- [FuchsiaFsBlobFsInfo],
- [FuchsiaFsMinFsInfo],
- [FuchsiaFsEmptyDataInfo],
- [FuchsiaFsEmptyAccountInfo],
- [FuchsiaFsReservedInfo],
- ],
- mandatory = True,
- ),
- "max_disk_size": attr.string(
- doc = "The maximum size the FVM can expand to at runtime.",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_fvm_standard.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_fvm_standard.bzl
deleted file mode 100644
index c1e74c1..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_fvm_standard.bzl
+++ /dev/null
@@ -1,64 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- ":providers.bzl",
- "FuchsiaFVMStandardInfo",
- "FuchsiaFsBlobFsInfo",
- "FuchsiaFsEmptyAccountInfo",
- "FuchsiaFsEmptyDataInfo",
- "FuchsiaFsMinFsInfo",
- "FuchsiaFsReservedInfo",
-)
-
-def _fuchsia_fvm_standard_impl(ctx):
- fvm_info = {
- "type": "standard",
- "name": ctx.attr.fvm_standard_name,
- }
- if ctx.attr.compress:
- fvm_info["compress"] = ctx.attr.compress
- if ctx.attr.resize_image_file_to_fit:
- fvm_info["resize_image_file_to_fit"] = ctx.attr.resize_image_file_to_fit
- if ctx.attr.truncate_to_length:
- fvm_info["truncate_to_length"] = int(ctx.attr.truncate_to_length)
- return [
- FuchsiaFVMStandardInfo(
- fvm_standard_name = ctx.attr.fvm_standard_name,
- filesystems = ctx.attr.filesystems,
- fvm_info = fvm_info,
- ),
- ]
-
-fuchsia_fvm_standard = rule(
- doc = """Generates a fvm with no modification.""",
- implementation = _fuchsia_fvm_standard_impl,
- provides = [FuchsiaFVMStandardInfo],
- attrs = {
- "fvm_standard_name": attr.string(
- doc = "Name of fvm file",
- mandatory = True,
- ),
- "filesystems": attr.label_list(
- doc = "Filesystems to use",
- providers = [
- [FuchsiaFsBlobFsInfo],
- [FuchsiaFsMinFsInfo],
- [FuchsiaFsEmptyDataInfo],
- [FuchsiaFsEmptyAccountInfo],
- [FuchsiaFsReservedInfo],
- ],
- mandatory = True,
- ),
- "compress": attr.bool(
- doc = "Whether to compress the fvm file.",
- ),
- "resize_image_file_to_fit": attr.bool(
- doc = "Shrink the FVM to fit exactly the contents",
- ),
- "truncate_to_length": attr.string(
- doc = "After the optional resize, truncate the file to this length",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_images_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_images_configuration.bzl
deleted file mode 100644
index 5975f04..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_images_configuration.bzl
+++ /dev/null
@@ -1,159 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for declaring an images configuration for a Fuchsia product."""
-
-load(
- ":providers.bzl",
- "FuchsiaAssemblyConfigInfo",
- "FuchsiaFVMNandInfo",
- "FuchsiaFVMSparseInfo",
- "FuchsiaFVMStandardInfo",
- "FuchsiaFsBlobFsInfo",
- "FuchsiaFsEmptyAccountInfo",
- "FuchsiaFsEmptyDataInfo",
- "FuchsiaFsMinFsInfo",
- "FuchsiaFsReservedInfo",
- "FuchsiaVbmetaInfo",
- "FuchsiaZbiInfo",
-)
-
-def _collect_file_systems(raw_filesystems, filesystems_dict):
- file_systems = []
- for filesystem in raw_filesystems:
- if FuchsiaFsBlobFsInfo in filesystem:
- raw_fs = filesystem[FuchsiaFsBlobFsInfo]
- filesystems_dict[raw_fs.blobfs_name] = raw_fs.blobfs_info
- file_systems.append(raw_fs.blobfs_name)
- elif FuchsiaFsEmptyAccountInfo in filesystem:
- raw_fs = filesystem[FuchsiaFsEmptyAccountInfo]
- empty_account_fs = {
- "type": "empty-account",
- "name": raw_fs.empty_account_name,
- }
- filesystems_dict[raw_fs.empty_account_name] = empty_account_fs
- file_systems.append(raw_fs.empty_account_name)
- elif FuchsiaFsEmptyDataInfo in filesystem:
- raw_fs = filesystem[FuchsiaFsEmptyDataInfo]
- empty_data = {
- "type": "empty-data",
- "name": raw_fs.empty_data_name,
- }
- filesystems_dict[raw_fs.empty_data_name] = empty_data
- file_systems.append(raw_fs.empty_data_name)
- elif FuchsiaFsMinFsInfo in filesystem:
- raw_fs = filesystem[FuchsiaFsMinFsInfo]
- filesystems_dict[raw_fs.minfs_name] = raw_fs.minfs_info
- file_systems.append(raw_fs.minfs_name)
- elif FuchsiaFsReservedInfo in filesystem:
- raw_fs = filesystem[FuchsiaFsReservedInfo]
- filesystems_dict[raw_fs.reserved_name] = raw_fs.reserved_info
- file_systems.append(raw_fs.reserved_name)
- return file_systems
-
-def _fuchsia_images_configuration_impl(ctx):
- if ctx.attr.images_config:
- return [
- DefaultInfo(
- files = depset(
- direct = [ctx.file.images_config] + ctx.files.images_config_extra_files,
- ),
- ),
- FuchsiaAssemblyConfigInfo(
- config = ctx.file.images_config,
- ),
- ]
-
- config_file = ctx.actions.declare_file(ctx.label.name + ".json")
- files = []
- images = []
- fvms = []
- filesystems = {}
- for image in ctx.attr.images:
- if FuchsiaZbiInfo in image:
- raw_image = image[FuchsiaZbiInfo]
- zbi_image = {
- "type": "zbi",
- "name": raw_image.zbi_name,
- "compression": raw_image.compression,
- }
- if raw_image.post_processing_script != None:
- post_processing_script = {
- "path": raw_image.post_processing_script.path,
- "args": raw_image.post_processing_args,
- }
- zbi_image["post_processing_script"] = post_processing_script
- files.append(raw_image.post_processing_script)
- images.append(zbi_image)
- elif FuchsiaVbmetaInfo in image:
- raw_image = image[FuchsiaVbmetaInfo]
- vbmeta_image = {
- "type": "vbmeta",
- "name": raw_image.vbmeta_name,
- }
- if raw_image.key != None:
- vbmeta_image["key"] = raw_image.key.path
- vbmeta_image["key_metadata"] = raw_image.key_metadata.path
- files += [raw_image.key, raw_image.key_metadata]
- images.append(vbmeta_image)
- elif FuchsiaFVMStandardInfo in image:
- raw_image = image[FuchsiaFVMStandardInfo]
- standard_fvm = dict(raw_image.fvm_info)
- standard_fvm["filesystems"] = _collect_file_systems(raw_image.filesystems, filesystems)
- fvms.append(standard_fvm)
- elif FuchsiaFVMSparseInfo in image:
- raw_image = image[FuchsiaFVMSparseInfo]
- sparse_fvm = dict(raw_image.fvm_info)
- sparse_fvm["filesystems"] = _collect_file_systems(raw_image.filesystems, filesystems)
- fvms.append(sparse_fvm)
- elif FuchsiaFVMNandInfo in image:
- raw_image = image[FuchsiaFVMNandInfo]
- nand_fvm = dict(raw_image.fvm_info)
- nand_fvm["filesystems"] = _collect_file_systems(raw_image.filesystems, filesystems)
- fvms.append(nand_fvm)
-
- fvm = {
- "type": "fvm",
- "filesystems": filesystems.values(),
- "outputs": fvms,
- }
- if ctx.attr.fvm_slice_size:
- fvm["slice_size"] = int(ctx.attr.fvm_slice_size)
- images.append(fvm)
- image_config = {"images": images}
- ctx.actions.write(config_file, json.encode(image_config))
- return [
- DefaultInfo(files = depset(direct = [config_file] + files)),
- FuchsiaAssemblyConfigInfo(config = config_file),
- ]
-
-fuchsia_images_configuration = rule(
- doc = "Declares an images configuration JSON file for use with ffx assembly.",
- implementation = _fuchsia_images_configuration_impl,
- provides = [FuchsiaAssemblyConfigInfo],
- attrs = {
- # TODO(jayzhuang): Remove this when we decide how to implement imagess configuration so it supports in-tree builds.
- "images_config": attr.label(
- doc = "Path to the generated images configuration file to use",
- allow_single_file = [".json"],
- ),
- "images_config_extra_files": attr.label(
- doc = "A list of files used to provide deps of this images configuration, only used when `images_config` is specified. Note the caller is responsible for ensuring the paths to these files are valid in `images_config`.",
- allow_files = True,
- ),
- "fvm_slice_size": attr.string(
- doc = "size of a slice within the FVM",
- ),
- "images": attr.label_list(
- doc = "Images to include in images configuration",
- providers = [
- [FuchsiaFVMNandInfo],
- [FuchsiaFVMStandardInfo],
- [FuchsiaFVMSparseInfo],
- [FuchsiaZbiInfo],
- [FuchsiaVbmetaInfo],
- ],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_partition.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_partition.bzl
deleted file mode 100644
index 3ea34f8..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_partition.bzl
+++ /dev/null
@@ -1,55 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- ":providers.bzl",
- "FuchsiaPartitionInfo",
-)
-
-SLOT = struct(
- A = "A", # Primary slot
- B = "B", # Alternate slot
- R = "R", # Recovery slot
-)
-
-PARTITION_TYPE = struct(
- ZBI = "ZBI",
- VBMETA = "VBMeta",
- FVM = "FVM",
-)
-
-def _fuchsia_partition_impl(ctx):
- partition = {
- "name": ctx.attr.partition_name,
- "type": ctx.attr.type,
- }
- if ctx.attr.slot != "":
- partition["slot"] = ctx.attr.slot
-
- return [
- FuchsiaPartitionInfo(
- partition = partition,
- ),
- ]
-
-fuchsia_partition = rule(
- doc = """Define a partition mapping from partition to image.""",
- implementation = _fuchsia_partition_impl,
- provides = [FuchsiaPartitionInfo],
- attrs = {
- "partition_name": attr.string(
- doc = "Name of the partition",
- mandatory = True,
- ),
- "slot": attr.string(
- doc = "The slot of the partition",
- values = [SLOT.A, SLOT.B, SLOT.R],
- ),
- "type": attr.string(
- doc = "Type of this partition",
- mandatory = True,
- values = [PARTITION_TYPE.ZBI, PARTITION_TYPE.VBMETA, PARTITION_TYPE.FVM],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_partitions_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_partitions_configuration.bzl
deleted file mode 100644
index 87680d5..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_partitions_configuration.bzl
+++ /dev/null
@@ -1,83 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for creating a partitions configuration."""
-
-load(
- ":providers.bzl",
- "FuchsiaAssemblyConfigInfo",
- "FuchsiaPartitionInfo",
-)
-
-def _collect_partitions(partition_targets):
- partitions = []
- for parition in partition_targets:
- partitions.append(parition[FuchsiaPartitionInfo].partition)
- return partitions
-
-def _fuchsia_partitions_configuration(ctx):
- if ctx.file.partition_config:
- return [
- DefaultInfo(files = depset(direct = [ctx.file.partition_config])),
- FuchsiaAssemblyConfigInfo(config = ctx.file.partition_config),
- ]
-
- partitions_config_file = ctx.actions.declare_file(ctx.label.name + "_partitions.json")
-
- partitions_config = {
- "hardware_revision": ctx.attr.hardware_revision,
- "bootstrap_partitions": _collect_partitions(ctx.attr.bootstrap_partitions),
- "bootloader_partitions": _collect_partitions(ctx.attr.bootloader_partitions),
- "partitions": _collect_partitions(ctx.attr.partitions),
- }
-
- unlock_credentials = []
- for credential in ctx.files.unlock_credentials:
- unlock_credentials.append(credential.path)
- partitions_config["unlock_credentials"] = unlock_credentials
- ctx.actions.write(partitions_config_file, json.encode(partitions_config))
-
- return [
- DefaultInfo(files = depset(direct = [partitions_config_file] + ctx.files.bootstrap_partitions + ctx.files.bootloader_partitions)),
- FuchsiaAssemblyConfigInfo(config = partitions_config_file),
- ]
-
-fuchsia_partitions_configuration = rule(
- doc = """Creates a partitions configuration.""",
- implementation = _fuchsia_partitions_configuration,
- attrs = {
- #TODO(lijiaming) After the partition configuration generation is moved OOT
- #, we can remove this workaround.
- "partition_config": attr.label(
- doc = "Relative path of built partition config file. If this file is" +
- "provided we will skip building it.",
- allow_single_file = [".json"],
- ),
- "bootstrap_partitions": attr.label_list(
- doc = "Partitions that only flashed in \"fuchsia\" configuration",
- providers = [
- [FuchsiaPartitionInfo],
- ],
- ),
- "bootloader_partitions": attr.label_list(
- doc = "List of bootloader partitions",
- providers = [
- [FuchsiaPartitionInfo],
- ],
- ),
- "partitions": attr.label_list(
- doc = "List of non-bootloader partitions",
- providers = [
- [FuchsiaPartitionInfo],
- ],
- ),
- "hardware_revision": attr.string(
- doc = "name of the hardware that needs to assert before flashing images",
- ),
- "unlock_credentials": attr.label_list(
- doc = "Zip files containing the fastboot unlock credentials",
- allow_files = [".zip"],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_connectivity_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_connectivity_configuration.bzl
deleted file mode 100644
index 788284f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_connectivity_configuration.bzl
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaConnectivityConfigInfo", "FuchsiaConnectivityWlanConfigInfo")
-
-def _fuchsia_platform_connectivity_configuration_impl(ctx):
- return [
- FuchsiaConnectivityConfigInfo(
- wlan = ctx.attr.wlan,
- ),
- ]
-
-fuchsia_platform_connectivity_configuration = rule(
- doc = """Generates an connectivity configuration.""",
- implementation = _fuchsia_platform_connectivity_configuration_impl,
- provides = [FuchsiaConnectivityConfigInfo],
- attrs = {
- "wlan": attr.label(
- providers = [FuchsiaConnectivityWlanConfigInfo],
- doc = "A bool value for legacy_privacy_support of wlan",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_connectivity_wlan_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_connectivity_wlan_configuration.bzl
deleted file mode 100644
index 201e56f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_connectivity_wlan_configuration.bzl
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaConnectivityWlanConfigInfo")
-
-def _fuchsia_platform_connectivity_wlan_configuration_impl(ctx):
- return [
- FuchsiaConnectivityWlanConfigInfo(
- legacy_privacy_support = ctx.attr.legacy_privacy_support,
- include_wlan_aibs = ctx.attr.include_wlan_aibs,
- ),
- ]
-
-fuchsia_platform_connectivity_wlan_configuration = rule(
- doc = """Generates an connectivity configuration.""",
- implementation = _fuchsia_platform_connectivity_wlan_configuration_impl,
- provides = [FuchsiaConnectivityWlanConfigInfo],
- attrs = {
- "legacy_privacy_support": attr.bool(
- doc = "A bool value for legacy_privacy_support of wlan",
- ),
- "include_wlan_aibs": attr.bool(
- doc = "A bool value for include_wlan_aibs of wlan",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_development_support_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_development_support_configuration.bzl
deleted file mode 100644
index 12fbacc..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_development_support_configuration.bzl
+++ /dev/null
@@ -1,23 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaDevelopmentSupportConfigInfo")
-
-def _fuchsia_platform_development_support_configuration_impl(ctx):
- return [
- FuchsiaDevelopmentSupportConfigInfo(
- enabled = ctx.attr.enabled,
- ),
- ]
-
-fuchsia_platform_development_support_configuration = rule(
- doc = """Generates an development_support configuration.""",
- implementation = _fuchsia_platform_development_support_configuration_impl,
- provides = [FuchsiaDevelopmentSupportConfigInfo],
- attrs = {
- "enabled": attr.bool(
- doc = "A bool value whether development_support is enabled",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_diagnostics_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_diagnostics_configuration.bzl
deleted file mode 100644
index 3efa34f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_diagnostics_configuration.bzl
+++ /dev/null
@@ -1,39 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaDiagnosticsConfigInfo")
-
-ARCHIVIST_TYPES = struct(
- BRINGUP = "bringup",
- DEFAULT_SERVICE = "default-service",
- NO_DETECT_SERVICE = "no-detect-service",
- NO_SERVICE = "no-service",
- LOW_MEM = "low-mem-default-service-config"
-)
-
-def _fuchsia_platform_diagnostics_configuration_impl(ctx):
- return [
- FuchsiaDiagnosticsConfigInfo(
- archivist = ctx.attr.archivist,
- ),
- ]
-
-fuchsia_platform_diagnostics_configuration = rule(
- doc = """Generates an diagnostics configuration.""",
- implementation = _fuchsia_platform_diagnostics_configuration_impl,
- provides = [FuchsiaDiagnosticsConfigInfo],
- attrs = {
- "archivist": attr.string(
- doc = "A string value for the archivist configuration flavor",
- values = [
- ARCHIVIST_TYPES.BRINGUP,
- ARCHIVIST_TYPES.DEFAULT_SERVICE,
- ARCHIVIST_TYPES.NO_DETECT_SERVICE,
- ARCHIVIST_TYPES.NO_SERVICE,
- ARCHIVIST_TYPES.LOW_MEM
- ],
- default = ARCHIVIST_TYPES.DEFAULT_SERVICE,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_identity_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_identity_configuration.bzl
deleted file mode 100644
index e86db62..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_identity_configuration.bzl
+++ /dev/null
@@ -1,33 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaIdentityConfigInfo")
-
-# Define Feature control option
-FEATURE_CONTROL = struct(
- DISABLED = "disabled",
- ALLOWED = "allowed",
- REQUIRED = "required",
-)
-
-def _fuchsia_platform_identity_configuration_impl(ctx):
- return [
- FuchsiaIdentityConfigInfo(
- password_pinweaver = ctx.attr.password_pinweaver,
- ),
- ]
-
-fuchsia_platform_identity_configuration = rule(
- doc = """Generates an identity configuration.""",
- implementation = _fuchsia_platform_identity_configuration_impl,
- provides = [FuchsiaIdentityConfigInfo],
- attrs = {
- "password_pinweaver": attr.string(
- doc = "Options for features that may either be forced on, forced" +
- "off, or allowed to be either on or off. Features default to disabled.",
- default = FEATURE_CONTROL.DISABLED,
- values = [FEATURE_CONTROL.DISABLED, FEATURE_CONTROL.ALLOWED, FEATURE_CONTROL.REQUIRED],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_input_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_input_configuration.bzl
deleted file mode 100644
index 29bd993..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_input_configuration.bzl
+++ /dev/null
@@ -1,44 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaInputConfigInfo")
-
-# Define input device types option
-INPUT_DEVICE_TYPE = struct(
- BUTTON = "button",
- KEYBOARD = "keyboard",
- MOUSE = "mouse",
- TOUCHSCREEN = "touchscreen",
-)
-
-def _fuchsia_platform_input_configuration_impl(ctx):
- if ctx.attr.idle_threshold_minutes == "":
- return [
- FuchsiaInputConfigInfo(
- supported_input_devices = ctx.attr.supported_input_devices,
- ),
- ]
- return [
- FuchsiaInputConfigInfo(
- supported_input_devices = ctx.attr.supported_input_devices,
- idle_threshold_minutes = ctx.attr.idle_threshold_minutes,
- ),
- ]
-
-fuchsia_platform_input_configuration = rule(
- doc = """Generates an input configuration.""",
- implementation = _fuchsia_platform_input_configuration_impl,
- provides = [FuchsiaInputConfigInfo],
- attrs = {
- "idle_threshold_minutes": attr.string(
- doc = "How much time has passed since the last user input activity" +
- "for the system to become idle.",
- ),
- "supported_input_devices": attr.string_list(
- doc = "Options for features that may either be forced on, forced" +
- "off, or allowed to be either on or off. Features default to disabled.",
- default = [],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_starnix_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_starnix_configuration.bzl
deleted file mode 100644
index d1d3426..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_platform_starnix_configuration.bzl
+++ /dev/null
@@ -1,23 +0,0 @@
-# Copyright 2023 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaStarnixConfigInfo")
-
-def _fuchsia_platform_starnix_configuration_impl(ctx):
- return [
- FuchsiaStarnixConfigInfo(
- enabled = ctx.attr.enabled,
- ),
- ]
-
-fuchsia_platform_starnix_configuration = rule(
- doc = """Generates a starnix configuration.""",
- implementation = _fuchsia_platform_starnix_configuration_impl,
- provides = [FuchsiaStarnixConfigInfo],
- attrs = {
- "enabled": attr.bool(
- doc = "Whether starnix support should be included",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_prebuilt_package.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_prebuilt_package.bzl
deleted file mode 100644
index 0226e79..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_prebuilt_package.bzl
+++ /dev/null
@@ -1,211 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Implement fuchsia_prebuilt_package() rule."""
-
-load("//fuchsia/private:providers.bzl", "FuchsiaPackageInfo")
-load("//fuchsia/private:package_publishing.bzl", "package_repo_path_from_label", "publish_package")
-load("//fuchsia/private/workflows:fuchsia_task_publish.bzl", "fuchsia_task_publish")
-
-_COMPONENT_VALIDATION_SCRIPT = """
-components=$($FAR list --archive=$OUTPUT_DIR/meta.far | grep -F meta/$COMPONENT.cm | wc -l)
-
-if [ $components -eq 0 ]; then
- echo
- echo "Component '$COMPONENT' is not included in the package!"
- echo
- exit 1
-fi
-touch $STAMP
-"""
-
-def _relative_file_name(ctx, filename):
- return ctx.label.name + "_expanded/" + filename
-
-def _validate_components_and_drivers(ctx, outdir):
- far = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"].far
- deps = []
- for component in ctx.attr.components + ctx.attr.drivers:
- stamp_file = ctx.actions.declare_file(_relative_file_name(ctx, component + "_stamp"))
-
- # NOTE: outdir is a ctx.actions.declare_directory() path, so declare
- # it as an input, even though only the `meta.far` inside it is used.
- # (There is no way to create a File() instance from it).
- #
- # This ensures the action that populates the directory is always run
- # properly before the run_shell() one below.
- ctx.actions.run_shell(
- inputs = [outdir, far],
- outputs = [stamp_file],
- command = _COMPONENT_VALIDATION_SCRIPT,
- env = {
- "FAR": far.path,
- "COMPONENT": component,
- "OUTPUT_DIR": outdir.path,
- "STAMP": stamp_file.path,
- },
- progress_message = "Validating the component %s" % component,
- )
- deps.append(stamp_file)
- return deps
-
-def _fuchsia_prebuilt_package_impl(ctx):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- far_archive = ctx.files.archive[0]
-
- # Technical note: `pm expand` below will populate its output directory
- # with multiple files whose name are content hashes and cannot be known in
- # advance, so use ctx.actions.declare_directory() to declare an output
- # directory for the expansion. This tells Bazel that all files present
- # in the directory after the command execution are outputs, and should
- # be copied from the sandbox to the corresponding final output location
- # in the output_base directory (otherwise, they would disappear once the
- # sandbox is destroyed).
- #
- # The top-level directory for this target will be computed from
- # `${label}_expanded/`, which, for a label like `//package/foo:bar`
- # will expand to something like this (relative to the sandbox execroot):
- #
- # `bazel-out/aarch64-opt/bin/package/foo/bar/bar_expanded`
- #
- # Inside this TARGET_OUT_DIR, the following is generated:
- #
- # $TARGET_OUT_DIR/
- # content/
- # A directory that contains the expanded content from the
- # prebuilt package, as well as a `package_manifest.json` file
- # that lists all entries, where source paths appear relative
- # to the execroot too, e.g.:
- #
- # "blobs": [
- # {
- # "source_path": "bazel-out/aarch64-opt/bin/package/foo/bar/bar_expanded/_content/meta.far",
- # "path": "meta/",
- # "merkle": "d0d73e04d89e393b71f2280831421ebe279e247265e25714c71fdc8961928822",
- # "size": 94288,
- # },
- # ...
- #
- # rebased_package_manifest.json
- # A version of _content/package_manifest.json that contains
- # source paths that are relative to an alternative `artifacts_base_path`
- # value. However, since the default value for this argument is just '.',
- # it will have the same content as `_content/package_manifest.json` in
- # most cases.
- #
- # Note that this file _cannot_ be inside `_content`, as Bazel
- # would complain otherwise, as it is generated by a different action
- # than the one that generated `_content/`.
- #
- # <component>_stamp
- # For each component listed in ctx.attr.components or
- # ctx.attr.drivers, a stamp file generated by the action that
- # verifies it belongs to the package.
- #
- output_dir = ctx.actions.declare_directory(_relative_file_name(ctx, "content"))
- output_files = [output_dir]
- output_files += _validate_components_and_drivers(ctx, output_dir)
-
- # extract the package
- ctx.actions.run(
- executable = sdk.pm,
- arguments = [
- "-o",
- output_dir.path,
- "-r",
- "fuchsia.com",
- "expand",
- far_archive.path,
- ],
- inputs = [far_archive],
- outputs = [
- output_dir,
- ],
- mnemonic = "FuchsiaPmExpand",
- progress_message = "expanding package for %{label}",
- )
-
- # rebase paths in package manifest
- rebased_package_manifest_json = ctx.actions.declare_file(_relative_file_name(ctx, "rebased_package_manifest.json"))
- ctx.actions.run(
- outputs = [rebased_package_manifest_json],
- inputs = [output_dir],
- executable = ctx.executable._rebase_package_manifest,
- arguments = [
- "--package-manifest",
- output_dir.path + "/package_manifest.json",
- "--updated-package-manifest",
- rebased_package_manifest_json.path,
- "--relative-base",
- ctx.attr.artifacts_base_path,
- ],
- )
- output_files.append(rebased_package_manifest_json)
-
- # Attempt to publish if told to do so
- repo_path = package_repo_path_from_label(ctx.attr._package_repo_path)
- if repo_path:
- stamp_file = publish_package(ctx, sdk.pm, repo_path, [rebased_package_manifest_json])
- output_files.append(stamp_file)
-
- return [
- DefaultInfo(files = depset(output_files)),
- FuchsiaPackageInfo(
- package_manifest = rebased_package_manifest_json,
- far_file = ctx.files.archive,
- components = ctx.attr.components,
- drivers = ctx.attr.drivers,
- ),
- ]
-
-_fuchsia_prebuilt_package = rule(
- doc = """Provides access to a fuchsia package from a prebuilt package archive (.far).
-""",
- implementation = _fuchsia_prebuilt_package_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "archive": attr.label(
- doc = "The fuchsia archive",
- allow_single_file = True,
- mandatory = True,
- ),
- "components": attr.string_list(
- doc = "components of this driver",
- default = [],
- ),
- "drivers": attr.string_list(
- doc = "drivers of this driver",
- default = [],
- ),
- "_package_repo_path": attr.label(
- doc = "The command line flag used to publish packages.",
- default = "//fuchsia:package_repo",
- ),
- "artifacts_base_path": attr.string(
- doc = "Artifacts base directories that items in config files are relative to.",
- default = ".",
- ),
- "_rebase_package_manifest": attr.label(
- default = "//fuchsia/tools:rebase_package_manifest",
- executable = True,
- cfg = "exec",
- ),
- },
-)
-
-def fuchsia_prebuilt_package(*, name, archive, components = [], drivers = [], artifacts_base_path = ".", **kwargs):
- _fuchsia_prebuilt_package(
- name = name,
- archive = archive,
- components = components,
- drivers = drivers,
- artifacts_base_path = artifacts_base_path,
- **kwargs
- )
-
- fuchsia_task_publish(
- name = "%s.publish" % name,
- packages = [name],
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_bundle.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_bundle.bzl
deleted file mode 100644
index 06a8263..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_bundle.bzl
+++ /dev/null
@@ -1,528 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for creating product bundle for flashing Fuchsia images to target devices."""
-
-load(
- ":providers.bzl",
- "FuchsiaAssemblyConfigInfo",
- "FuchsiaProductBundleInfo",
- "FuchsiaProductImageInfo",
- "FuchsiaScrutinyConfigInfo",
-)
-
-def _scrutiny_validation(
- ctx,
- ffx_tool,
- pb_out_dir,
- scrutiny_config,
- is_recovery = False):
- deps = []
- ffx_invocation = [
- ffx_tool.path,
- "scrutiny",
- "verify",
- ]
- if is_recovery:
- ffx_invocation += ["--recovery"]
-
- deps += [_verify_bootfs_filelist(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- scrutiny_config.bootfs_files,
- scrutiny_config.bootfs_packages,
- )]
- deps += [_verify_kernel_cmdline(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- scrutiny_config.kernel_cmdline,
- )]
- deps += _verify_route_sources(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- scrutiny_config.routes_config_golden,
- )
- deps += _verify_component_resolver_allowlist(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- scrutiny_config.component_resolver_allowlist,
- )
- deps += _verify_routes(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- scrutiny_config.component_route_exceptions,
- scrutiny_config.component_tree_config,
- )
- deps += _verify_base_packages(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- scrutiny_config.base_packages,
- )
- deps += _verify_structured_config(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- scrutiny_config.structured_config_policy,
- )
- deps += _extract_structured_config(
- ctx,
- ffx_tool,
- pb_out_dir,
- is_recovery,
- )
- return deps
-
-def _verify_bootfs_filelist(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- zbi_bootfs_filelist_goldens,
- zbi_bootfs_packages_goldens):
- stamp_file = ctx.actions.declare_file(ctx.label.name + "_bootfs.stamp")
- _ffx_invocation = []
- _ffx_invocation.extend(ffx_invocation)
- _ffx_invocation += [
- "--stamp",
- stamp_file.path,
- "bootfs",
- "--product-bundle",
- pb_out_dir.path,
- ]
-
- for golden_file in zbi_bootfs_filelist_goldens:
- _ffx_invocation += [
- "--golden",
- golden_file.path,
- ]
- for golden_package in zbi_bootfs_packages_goldens:
- _ffx_invocation += [
- "--golden-packages",
- golden_package.path,
- ]
-
- script_lines = [
- "set -e",
- " ".join(_ffx_invocation),
- ]
- inputs = [ffx_tool, pb_out_dir] + zbi_bootfs_filelist_goldens + zbi_bootfs_packages_goldens
-
- ctx.actions.run_shell(
- inputs = inputs,
- outputs = [stamp_file],
- command = "\n".join(script_lines),
- progress_message = "Verify Bootfs file list for %s" % ctx.label.name,
- )
- return stamp_file
-
-def _verify_kernel_cmdline(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- zbi_kernel_cmdline_goldens):
- stamp_file = ctx.actions.declare_file(ctx.label.name + "_kernel.stamp")
- _ffx_invocation = []
- _ffx_invocation.extend(ffx_invocation)
- _ffx_invocation += [
- "--stamp",
- stamp_file.path,
- "kernel-cmdline",
- "--product-bundle",
- pb_out_dir.path,
- ]
-
- for golden_file in zbi_kernel_cmdline_goldens:
- _ffx_invocation += [
- "--golden",
- golden_file.path,
- ]
-
- script_lines = [
- "set -e",
- " ".join(_ffx_invocation),
- ]
- inputs = [ffx_tool, pb_out_dir] + zbi_kernel_cmdline_goldens
-
- ctx.actions.run_shell(
- inputs = inputs,
- outputs = [stamp_file],
- command = "\n".join(script_lines),
- progress_message = "Verify Kernel Cmdline for %s" % ctx.label.name,
- )
- return stamp_file
-
-def _verify_route_sources(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- routes_config_golden):
- stamp_file = ctx.actions.declare_file(ctx.label.name + "_route.stamp")
- tmp_dir = ctx.actions.declare_directory(ctx.label.name + "_route.tmp")
- _ffx_invocation = []
- _ffx_invocation.extend(ffx_invocation)
- _ffx_invocation += [
- "--stamp",
- stamp_file.path,
- "--tmp-dir",
- tmp_dir.path,
- "route-sources",
- "--product-bundle",
- pb_out_dir.path,
- "--config",
- routes_config_golden.path,
- ]
-
- script_lines = [
- "set -e",
- " ".join(_ffx_invocation),
- ]
- inputs = [ffx_tool, pb_out_dir, routes_config_golden]
-
- ctx.actions.run_shell(
- inputs = inputs,
- outputs = [stamp_file, tmp_dir],
- command = "\n".join(script_lines),
- progress_message = "Verify Route sources for %s" % ctx.label.name,
- )
- return [stamp_file, tmp_dir]
-
-def _verify_component_resolver_allowlist(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- component_resolver_allowlist):
- stamp_file = ctx.actions.declare_file(ctx.label.name + "_component_resolver.stamp")
- tmp_dir = ctx.actions.declare_directory(ctx.label.name + "_component_resolver.tmp")
- _ffx_invocation = []
- _ffx_invocation.extend(ffx_invocation)
- _ffx_invocation += [
- "--stamp",
- stamp_file.path,
- "--tmp-dir",
- tmp_dir.path,
- "component-resolvers",
- "--product-bundle",
- pb_out_dir.path,
- "--allowlist",
- component_resolver_allowlist.path,
- ]
-
- script_lines = [
- "set -e",
- " ".join(_ffx_invocation),
- ]
- inputs = [ffx_tool, pb_out_dir, component_resolver_allowlist]
-
- ctx.actions.run_shell(
- inputs = inputs,
- outputs = [stamp_file, tmp_dir],
- command = "\n".join(script_lines),
- progress_message = "Verify Component Resolver for %s" % ctx.label.name,
- )
- return [stamp_file, tmp_dir]
-
-def _verify_routes(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- allow_lists,
- component_tree_config):
- stamp_file = ctx.actions.declare_file(ctx.label.name + "_routes.stamp")
- tmp_dir = ctx.actions.declare_directory(ctx.label.name + "_routes.tmp")
- _ffx_invocation = []
- _ffx_invocation.extend(ffx_invocation)
- _ffx_invocation += [
- "--stamp",
- stamp_file.path,
- "--tmp-dir",
- tmp_dir.path,
- "routes",
- "--product-bundle",
- pb_out_dir.path,
- ]
- if component_tree_config:
- _ffx_invocation += [
- "--component-tree-config",
- component_tree_config.path,
- ]
- for allow_list in allow_lists:
- _ffx_invocation += [
- "--allowlist",
- allow_list.path,
- ]
-
- script_lines = [
- "set -e",
- " ".join(_ffx_invocation),
- ]
- inputs = [ffx_tool, pb_out_dir, component_tree_config] + allow_lists
-
- ctx.actions.run_shell(
- inputs = inputs,
- outputs = [stamp_file, tmp_dir],
- command = "\n".join(script_lines),
- progress_message = "Verify Routes for %s" % ctx.label.name,
- )
- return [stamp_file, tmp_dir]
-
-def _verify_base_packages(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- base_packages):
- stamp_file = ctx.actions.declare_file(ctx.label.name + "_static_pkgs.stamp")
- tmp_dir = ctx.actions.declare_directory(ctx.label.name + "_static_pkgs.tmp")
- _ffx_invocation = []
- _ffx_invocation.extend(ffx_invocation)
- _ffx_invocation += [
- "--stamp",
- stamp_file.path,
- "--tmp-dir",
- tmp_dir.path,
- "static-pkgs",
- "--product-bundle",
- pb_out_dir.path,
- "--golden",
- base_packages.path,
- ]
-
- script_lines = [
- "set -e",
- " ".join(_ffx_invocation),
- ]
- inputs = [ffx_tool, pb_out_dir, base_packages]
-
- ctx.actions.run_shell(
- inputs = inputs,
- outputs = [stamp_file, tmp_dir],
- command = "\n".join(script_lines),
- progress_message = "Verify Static pkgs for %s" % ctx.label.name,
- )
- return [stamp_file, tmp_dir]
-
-def _verify_structured_config(
- ctx,
- ffx_invocation,
- ffx_tool,
- pb_out_dir,
- structured_config_policy):
- stamp_file = ctx.actions.declare_file(ctx.label.name + "_structured_config.stamp")
- tmp_dir = ctx.actions.declare_directory(ctx.label.name + "_structured_config.tmp")
- _ffx_invocation = []
- _ffx_invocation.extend(ffx_invocation)
- _ffx_invocation += [
- "--stamp",
- stamp_file.path,
- "--tmp-dir",
- tmp_dir.path,
- "structured-config",
- "--product-bundle",
- pb_out_dir.path,
- "--policy",
- structured_config_policy.path,
- ]
-
- script_lines = [
- "set -e",
- " ".join(_ffx_invocation),
- ]
- inputs = [ffx_tool, pb_out_dir, structured_config_policy]
-
- ctx.actions.run_shell(
- inputs = inputs,
- outputs = [stamp_file, tmp_dir],
- command = "\n".join(script_lines),
- progress_message = "Verify structured config for %s" % ctx.label.name,
- )
- return [stamp_file, tmp_dir]
-
-def _extract_structured_config(ctx, ffx_tool, pb_out_dir, is_recovery):
- structured_config = ctx.actions.declare_file(ctx.label.name + "_structured_config")
- depfile = ctx.actions.declare_file(ctx.label.name + "_depfile")
- ffx_invocation = [
- ffx_tool.path,
- "scrutiny",
- "extract",
- "structured-config",
- "--product-bundle",
- pb_out_dir.path,
- "--output",
- structured_config.path,
- # These args are currently required, but the outputs are ignored.
- "--build-path",
- pb_out_dir.path,
- "--depfile",
- depfile.path,
- ]
-
- if is_recovery:
- ffx_invocation += ["--recovery"]
-
- script_lines = [
- "set -e",
- " ".join(ffx_invocation),
- ]
- inputs = [ffx_tool, pb_out_dir]
-
- ctx.actions.run_shell(
- inputs = inputs,
- outputs = [structured_config, depfile],
- command = "\n".join(script_lines),
- progress_message = "Extract structured config for %s" % ctx.label.name,
- )
- return [structured_config, depfile]
-
-def _fuchsia_product_bundle_impl(ctx):
- partitions_configuration = ctx.attr.partitions_config[FuchsiaAssemblyConfigInfo].config
- system_a_out = ctx.attr.product_image[FuchsiaProductImageInfo].images_out
- ffx_tool = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"].ffx
- pb_out_dir = ctx.actions.declare_directory(ctx.label.name + "_out")
-
- # Gather all the arguments to pass to ffx.
- ffx_invocation = [
- "$ORIG_DIR/$FFX",
- "--config \"product.experimental=true\"",
- "product",
- "create",
- "--partitions $ORIG_DIR/$PARTITIONS_PATH",
- "--system-a $ORIG_DIR/$SYSTEM_A_MANIFEST",
- "--out-dir $ORIG_DIR/$OUTDIR",
- ]
-
- # Gather the environment variables needed in the script.
- env = {
- "FFX": ffx_tool.path,
- "OUTDIR": pb_out_dir.path,
- "PARTITIONS_PATH": partitions_configuration.path,
- "SYSTEM_A_MANIFEST": system_a_out.path + "/images.json",
- "ARTIFACTS_BASE_PATH": ctx.attr.artifacts_base_path,
- }
-
- # Gather all the inputs.
- inputs = [partitions_configuration] + ctx.files.product_image
-
- # If recovery is supplied, add it to the product bundle.
- if ctx.attr.recovery != None:
- system_r_out = ctx.attr.recovery[FuchsiaProductImageInfo].images_out
- ffx_invocation.append("--system-r $ORIG_DIR/$SYSTEM_R_MANIFEST")
- env["SYSTEM_R_MANIFEST"] = system_r_out.path + "/images.json"
- inputs.extend(ctx.files.recovery)
-
- # If update info is supplied, add it to the product bundle.
- if ctx.file.update_version_file != None:
- if ctx.file.repository_keys == None:
- fail("Repository keys must be supplied in order to build an update package")
-
- ffx_invocation.extend([
- "--update-package-version-file $ORIG_DIR/$UPDATE_VERSION_FILE",
- "--update-package-epoch $UPDATE_EPOCH",
- ])
- env["UPDATE_VERSION_FILE"] = ctx.file.update_version_file.path
- env["UPDATE_EPOCH"] = ctx.attr.update_epoch
- inputs.append(ctx.file.update_version_file)
-
- # If a repository is supplied, add it to the product bundle.
- if ctx.file.repository_keys != None:
- ffx_invocation.append("--tuf-keys $ORIG_DIR/$REPOKEYS")
- env["REPOKEYS"] = ctx.file.repository_keys.path
- inputs.append(ctx.file.repository_keys)
-
- script_lines = [
- "set -e",
- "ORIG_DIR=$(pwd)",
- "cd $ARTIFACTS_BASE_PATH",
- " ".join(ffx_invocation),
- ]
-
- if ctx.file.repository_keys != None:
- script_lines.append("cp -r $ORIG_DIR/$REPOKEYS $ORIG_DIR/$OUTDIR")
- script = "\n".join(script_lines)
-
- ctx.actions.run_shell(
- inputs = inputs,
- outputs = [pb_out_dir],
- command = script,
- env = env,
- progress_message = "Creating product bundle for %s" % ctx.label.name,
- )
- deps = [pb_out_dir]
-
- # Scrutiny Validation
- if ctx.attr.product_image_scrutiny_config:
- product_image_scrutiny_config = ctx.attr.product_image_scrutiny_config[FuchsiaScrutinyConfigInfo]
- deps += _scrutiny_validation(ctx, ffx_tool, pb_out_dir, product_image_scrutiny_config)
- if ctx.attr.recovery_scrutiny_config:
- recovery_scrutiny_config = ctx.attr.recovery_scrutiny_config[FuchsiaScrutinyConfigInfo]
- deps += _scrutiny_validation(ctx, ffx_tool, pb_out_dir, recovery_scrutiny_config, True)
-
- return [DefaultInfo(files = depset(direct = deps)), FuchsiaProductBundleInfo(
- product_bundle = pb_out_dir,
- is_remote = False,
- )]
-
-fuchsia_product_bundle = rule(
- doc = """Creates pb for flashing Fuchsia images to target devices.""",
- implementation = _fuchsia_product_bundle_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "partitions_config": attr.label(
- doc = "Partitions config to use, can be a fuchsia_partitions_configuration target, or a JSON file",
- allow_single_file = [".json"],
- mandatory = True,
- ),
- "product_image": attr.label(
- doc = "fuchsia_product_image target to put in slot A",
- providers = [FuchsiaProductImageInfo],
- mandatory = True,
- ),
- "recovery": attr.label(
- doc = "fuchsia_product_image target to put in slot R",
- providers = [FuchsiaProductImageInfo],
- ),
- "artifacts_base_path": attr.string(
- doc = "Artifacts base directories that items in config files are relative to.",
- default = ".",
- ),
- "repository_keys": attr.label(
- doc = "Directory of repository keys",
- allow_single_file = True,
- default = None,
- ),
- "update_version_file": attr.label(
- doc = "version file needed to create update package",
- allow_single_file = True,
- default = None,
- ),
- "update_epoch": attr.string(
- doc = "epoch needed to create update package",
- default = "1",
- ),
- "product_image_scrutiny_config": attr.label(
- doc = "Scrutiny config for slot A",
- providers = [FuchsiaScrutinyConfigInfo],
- ),
- "recovery_scrutiny_config": attr.label(
- doc = "Scrutiny config for recovery",
- providers = [FuchsiaScrutinyConfigInfo],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_configuration.bzl
deleted file mode 100644
index f89a22a..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_configuration.bzl
+++ /dev/null
@@ -1,322 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- ":providers.bzl",
- "FuchsiaAssembledPackageInfo",
- "FuchsiaConnectivityConfigInfo",
- "FuchsiaConnectivityWlanConfigInfo",
- "FuchsiaDevelopmentSupportConfigInfo",
- "FuchsiaDiagnosticsConfigInfo",
- "FuchsiaIdentityConfigInfo",
- "FuchsiaInputConfigInfo",
- "FuchsiaProductConfigInfo",
- "FuchsiaStarnixConfigInfo",
-)
-load("//fuchsia/private:providers.bzl", "FuchsiaPackageInfo")
-
-# Define build types
-BUILD_TYPES = struct(
- ENG = "eng",
- USER = "user",
- USER_DEBUG = "userdebug",
-)
-
-def _create_pkg_detail(dep):
- if FuchsiaPackageInfo in dep:
- return {"manifest": dep[FuchsiaPackageInfo].package_manifest.path}
-
- package = dep[FuchsiaAssembledPackageInfo].package
- configs = dep[FuchsiaAssembledPackageInfo].configs
- config_data = []
- for config in configs:
- config_data.append(
- {
- "destination": config.destination,
- "source": config.source.path,
- },
- )
- return {"manifest": package.package_manifest.path, "config_data": config_data}
-
-def _collect_file_deps(dep):
- if FuchsiaPackageInfo in dep:
- return [dep[FuchsiaPackageInfo].package_manifest]
-
- package = dep[FuchsiaAssembledPackageInfo].package
- configs = dep[FuchsiaAssembledPackageInfo].configs
- deps = [package.package_manifest]
- for config in configs:
- deps.append(config.source)
- return deps
-
-def _create_platform_config(ctx):
- platform = {}
- platform["build_type"] = ctx.attr.build_type
- if len(ctx.attr.additional_serial_log_tags) > 0:
- platform["additional_serial_log_tags"] = ctx.attr.additional_serial_log_tags
- if ctx.attr.identity != None:
- platform["identity"] = ctx.attr.identity[FuchsiaIdentityConfigInfo]
- if ctx.attr.input != None:
- platform["input"] = ctx.attr.input[FuchsiaInputConfigInfo]
- if ctx.attr.connectivity != None:
- connectivity_config = ctx.attr.connectivity[FuchsiaConnectivityConfigInfo]
- platform["connectivity"] = {
- "wlan": connectivity_config.wlan[FuchsiaConnectivityWlanConfigInfo],
- }
- if ctx.attr.development_support != None:
- platform["development_support"] = ctx.attr.development_support[FuchsiaDevelopmentSupportConfigInfo]
- if ctx.attr.starnix != None:
- platform["starnix"] = ctx.attr.starnix[FuchsiaStarnixConfigInfo]
- if ctx.attr.diagnostics != None:
- diagnostics_config = ctx.attr.diagnostics[FuchsiaDiagnosticsConfigInfo]
- platform["diagnostics"] = diagnostics_config
-
- return platform
-
-def _create_product_config_from_pre_existing_config(ctx):
- # We only support adding base package for now.
- deps = []
- deps += ctx.files.product_config_files
- base_pkg_details = []
- for dep in ctx.attr.base_packages:
- base_pkg_details.append(_create_pkg_detail(dep))
- deps += _collect_file_deps(dep)
- product_config_file = ctx.actions.declare_file(ctx.label.name + "_product_config.json")
- artifact_base_path = product_config_file.path
- if ctx.attr.artifact_base_path:
- artifact_base_path = ctx.file.artifact_base_path.path
-
- ctx.actions.run(
- outputs = [product_config_file],
- inputs = [ctx.file.product_config],
- executable = ctx.executable._add_base_pkgs,
- arguments = [
- "--product-config",
- ctx.file.product_config.path,
- "--base-details",
- str(base_pkg_details),
- "--updated-product-config",
- product_config_file.path,
- "--relative-base",
- artifact_base_path,
- ],
- )
- deps.append(product_config_file)
-
- return [
- DefaultInfo(
- files = depset(
- direct = deps,
- ),
- ),
- FuchsiaProductConfigInfo(
- product_config = product_config_file,
- ),
- ]
-
-def _fuchsia_product_configuration_impl(ctx):
- if ctx.attr.product_config:
- return _create_product_config_from_pre_existing_config(ctx)
-
- product_config = {}
- product_config["platform"] = _create_platform_config(ctx)
-
- product = {}
- if ctx.attr.session_url:
- product["session_url"] = ctx.attr.session_url
- packages = {}
-
- deps = []
- base_pkg_details = []
- for dep in ctx.attr.base_packages:
- base_pkg_details.append(_create_pkg_detail(dep))
- deps += _collect_file_deps(dep)
- packages["base"] = base_pkg_details
-
- cache_pkg_details = []
- for dep in ctx.attr.cache_packages:
- cache_pkg_details.append(_create_pkg_detail(dep))
- deps += _collect_file_deps(dep)
- packages["cache"] = cache_pkg_details
-
- product["packages"] = packages
-
- driver_details = []
- for dep in ctx.attr.driver_packages:
- driver_details.append(
- {
- "package": dep[FuchsiaPackageInfo].package_manifest.path,
- "components": dep[FuchsiaPackageInfo].drivers,
- },
- )
- deps += [dep[FuchsiaPackageInfo].package_manifest]
- product["drivers"] = driver_details
- product_config["product"] = product
-
- product_config_file_rebased = ctx.actions.declare_file(ctx.label.name + "_product_config_rebased.json")
- content = json.encode_indent(product_config, indent = " ")
-
- if ctx.attr.artifact_base_path:
- artifact_base_path = ctx.file.artifact_base_path.path
- ctx.actions.run(
- outputs = [product_config_file_rebased],
- executable = ctx.executable._rebase_product_config,
- arguments = [
- "--product-config-content",
- content,
- "--product-config-path",
- product_config_file_rebased.path,
- "--relative-base",
- artifact_base_path,
- ],
- )
- else:
- ctx.actions.write(product_config_file_rebased, content)
-
- product_config_file = ctx.actions.declare_file(ctx.label.name + "_product_config.json")
- ctx.actions.run(
- inputs = [product_config_file_rebased],
- outputs = [product_config_file],
- executable = ctx.executable._add_parameters,
- arguments = [
- "--product-config-path",
- product_config_file_rebased.path,
- "--additional-bool",
- str(ctx.attr.additional_platform_flags_bool),
- "--additional-string",
- str(ctx.attr.additional_platform_flags_string),
- "--additional-int",
- str(ctx.attr.additional_platform_flags_int),
- "--output",
- product_config_file.path,
- ],
- )
-
- deps.append(product_config_file)
- return [
- DefaultInfo(
- files = depset(
- direct = deps,
- ),
- ),
- FuchsiaProductConfigInfo(
- product_config = product_config_file,
- ),
- ]
-
-fuchsia_product_configuration = rule(
- doc = """Generates a product configuration file.""",
- implementation = _fuchsia_product_configuration_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "build_type": attr.string(
- doc = "Build type of this product.",
- values = [BUILD_TYPES.ENG, BUILD_TYPES.USER, BUILD_TYPES.USER_DEBUG],
- ),
- "identity": attr.label(
- doc = "Identity configuration.",
- providers = [FuchsiaIdentityConfigInfo],
- default = None,
- ),
- "input": attr.label(
- doc = "Input Configuration.",
- providers = [FuchsiaInputConfigInfo],
- default = None,
- ),
- "connectivity": attr.label(
- doc = "Connectivity Configuration.",
- providers = [FuchsiaConnectivityConfigInfo],
- default = None,
- ),
- "diagnostics": attr.label(
- doc = "Diagnostics Configuration.",
- providers = [FuchsiaDiagnosticsConfigInfo],
- default = None,
- ),
- "development_support": attr.label(
- doc = "Developement Support Configuration.",
- providers = [FuchsiaDevelopmentSupportConfigInfo],
- default = None,
- ),
- "starnix": attr.label(
- doc = "Starnix Configuration.",
- providers = [FuchsiaStarnixConfigInfo],
- default = None,
- ),
- "base_packages": attr.label_list(
- doc = "Fuchsia packages to be included in base.",
- providers = [
- [FuchsiaAssembledPackageInfo],
- [FuchsiaPackageInfo],
- ],
- default = [],
- ),
- "cache_packages": attr.label_list(
- doc = "Fuchsia packages to be included in cache.",
- providers = [
- [FuchsiaAssembledPackageInfo],
- [FuchsiaPackageInfo],
- ],
- default = [],
- ),
- "driver_packages": attr.label_list(
- doc = "Driver packages to include in product.",
- providers = [FuchsiaPackageInfo],
- default = [],
- ),
- "session_url": attr.string(
- doc = "Session url string that will be included in product_config.json.",
- ),
- #TODO(lijiaming) After the product configuration generation is moved OOT
- #, we can remove this workaround.
- "product_config": attr.label(
- doc = "Relative path of built product_config files. If this file is" +
- "provided we will skip building product config from scratch.",
- allow_single_file = [".json"],
- ),
- "product_config_files": attr.label(
- doc = "a list of files used to provide deps of product configuration.",
- allow_files = True,
- ),
- "artifact_base_path": attr.label(
- doc = "The artifact base directory. The paths in the product" +
- "configuration will be relative to this directory. If this" +
- "path is not provided, paths in product configuration will be" +
- "relative to product configuration itself",
- allow_single_file = True,
- default = None,
- ),
- "additional_serial_log_tags": attr.string_list(
- doc = """A list of logging tags to forward to the serial console.""",
- default = [],
- ),
- "additional_platform_flags_bool": attr.string_dict(
- doc = """This is a dictionary map from json path of platform config
-to a bool value. The values are passed in as string formed true/false.""",
- ),
- "additional_platform_flags_string": attr.string_dict(
- doc = """This is a dictionary map from json path of platform config
-to a string value. """,
- ),
- "additional_platform_flags_int": attr.string_dict(
- doc = """This is a dictionary map from json path of platform config
-to a int value. The values are passed in as an int string""",
- ),
- "_rebase_product_config": attr.label(
- default = "//fuchsia/tools:rebase_product_config",
- executable = True,
- cfg = "exec",
- ),
- "_add_parameters": attr.label(
- default = "//fuchsia/tools:add_parameters",
- executable = True,
- cfg = "exec",
- ),
- "_add_base_pkgs": attr.label(
- default = "//fuchsia/tools:add_base_pkgs",
- executable = True,
- cfg = "exec",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_image.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_image.bzl
deleted file mode 100644
index 2e7e24f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_image.bzl
+++ /dev/null
@@ -1,162 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for defining a pavable Fuchsia image."""
-
-load(
- ":providers.bzl",
- "FuchsiaAssemblyConfigInfo",
- "FuchsiaBoardConfigInfo",
- "FuchsiaProductAssemblyBundleInfo",
- "FuchsiaProductConfigInfo",
- "FuchsiaProductImageInfo",
-)
-
-# Base source for running ffx assembly product
-_PRODUCT_ASSEMBLY_RUNNER_SH_TEMPLATE = """
-set -e
-
-ORIG_DIR=$(pwd)
-cd $ARTIFACTS_BASE_PATH
-
-mkdir -p $FFX_ISOLATE_DIR
-
-$ORIG_DIR/$FFX \
- --config "assembly_enabled=true,sdk.root=$ORIG_DIR/$SDK_ROOT" \
- --isolate-dir $FFX_ISOLATE_DIR \
- assembly \
- product \
- --product $ORIG_DIR/$PRODUCT_CONFIG_PATH \
- {board_config_arg} \
- --legacy-bundle $ORIG_DIR/$LEGACY_AIB \
- --input-bundles-dir $ORIG_DIR/$PLATFORM_AIB_DIR \
- --outdir $ORIG_DIR/$OUTDIR
-
-$ORIG_DIR/$FFX \
- --config "assembly_enabled=true,sdk.root=$ORIG_DIR/$SDK_ROOT" \
- --isolate-dir $FFX_ISOLATE_DIR \
- assembly \
- create-system \
- --image-assembly-config $ORIG_DIR/$OUTDIR/image_assembly.json \
- --images $ORIG_DIR/$IMAGES_CONFIG_PATH \
- --outdir $ORIG_DIR/$OUTDIR
-
-"""
-
-def _fuchsia_product_image_impl(ctx):
- fuchsia_toolchain = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- ffx_tool = fuchsia_toolchain.ffx
- legacy_aib = ctx.attr.legacy_aib[FuchsiaProductAssemblyBundleInfo]
- platform_aibs = ctx.attr.platform_aibs[FuchsiaProductAssemblyBundleInfo]
- out_dir = ctx.actions.declare_directory(ctx.label.name + "_out")
-
- # Product Assembly and create-system
- images_config_info = ctx.attr.image[FuchsiaAssemblyConfigInfo]
- images_config_file = images_config_info.config
- product_config_file = ctx.attr.product_config[FuchsiaProductConfigInfo].product_config
- board_config_file = ctx.attr.board_config[FuchsiaBoardConfigInfo].board_config if ctx.attr.board_config else None
-
- shell_src = _PRODUCT_ASSEMBLY_RUNNER_SH_TEMPLATE.format(
- board_config_arg = "--board-info $ORIG_DIR/$BOARD_CONFIG_PATH" if board_config_file else "",
- )
-
- # NOTE: The `cmc` host tool is used by `ffx`, which finds its location
- # by parsing the _sdk_manifest, then the `cmc_manifest` one.
- ffx_inputs = [
- ctx.file._sdk_manifest,
- ffx_tool,
- fuchsia_toolchain.cmc,
- fuchsia_toolchain.cmc_manifest,
- product_config_file,
- ]
- if board_config_file:
- ffx_inputs.append(board_config_file)
-
- ffx_inputs += legacy_aib.files
- ffx_inputs += platform_aibs.files
- ffx_inputs += ctx.files.product_config
- ffx_inputs += ctx.files.image
-
- ffx_isolate_dir = ctx.actions.declare_directory(ctx.label.name + "_ffx_isolate_dir")
-
- shell_env = {
- "FFX": ffx_tool.path,
- "SDK_ROOT": ctx.attr._sdk_manifest.label.workspace_root,
- "FFX_ISOLATE_DIR": ffx_isolate_dir.path,
- "OUTDIR": out_dir.path,
- "PRODUCT_CONFIG_PATH": product_config_file.path,
- "LEGACY_AIB": legacy_aib.dir.path,
- "PLATFORM_AIB_DIR": platform_aibs.dir.path,
- "IMAGES_CONFIG_PATH": images_config_file.path,
- "ARTIFACTS_BASE_PATH": ctx.attr.artifacts_base_path,
- }
- if board_config_file:
- shell_env["BOARD_CONFIG_PATH"] = board_config_file.path
-
- ctx.actions.run_shell(
- inputs = ffx_inputs,
- outputs = [
- out_dir,
- # Isolate dirs contain useful debug files like logs, so include it
- # in outputs.
- ffx_isolate_dir,
- ],
- command = shell_src,
- env = shell_env,
- progress_message = "Product Assembly and create-system for %s" % ctx.label.name,
- )
-
- return [
- DefaultInfo(files = depset(direct = [out_dir] + ctx.files.product_config)),
- OutputGroupInfo(
- debug_files = depset([ffx_isolate_dir]),
- all_files = depset([out_dir, ffx_isolate_dir] + ctx.files.product_config),
- ),
- FuchsiaProductImageInfo(
- images_out = out_dir,
- ),
- ]
-
-fuchsia_product_image = rule(
- doc = """Declares a Fuchsia product image.""",
- implementation = _fuchsia_product_image_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- provides = [FuchsiaProductImageInfo],
- attrs = {
- "product_config": attr.label(
- doc = "A product configuration target.",
- providers = [FuchsiaProductConfigInfo],
- mandatory = True,
- ),
- "board_config": attr.label(
- doc = "A board configuration target.",
- providers = [FuchsiaBoardConfigInfo],
- # TODO(fxb/119590): Make mandatory once soft transition completes.
- mandatory = False,
- ),
- "image": attr.label(
- doc = "A fuchsia_images_configuration target.",
- providers = [FuchsiaAssemblyConfigInfo],
- mandatory = True,
- ),
- "legacy_aib": attr.label(
- doc = "Legacy AIB for this product.",
- providers = [FuchsiaProductAssemblyBundleInfo],
- mandatory = True,
- ),
- "platform_aibs": attr.label(
- doc = "Platform AIBs for this product.",
- providers = [FuchsiaProductAssemblyBundleInfo],
- mandatory = True,
- ),
- "artifacts_base_path": attr.string(
- doc = "Artifacts base directories that items in config files are relative to.",
- default = ".",
- ),
- "_sdk_manifest": attr.label(
- allow_single_file = True,
- default = "@fuchsia_sdk//:meta/manifest.json",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_size_check.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_size_check.bzl
deleted file mode 100644
index 7b54fc0..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_product_size_check.bzl
+++ /dev/null
@@ -1,53 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for running size checker on given image."""
-
-load(":providers.bzl", "FuchsiaProductImageInfo")
-
-# Command for running ffx assembly size-check product.
-_SIZE_CHECKER_RUNNER_SH = """
-set -e
-
-$FFX \
- --config "assembly_enabled=true" \
- assembly \
- size-check \
- product \
- --assembly-manifest $IMAGES_PATH \
- --size-breakdown-output $SIZE_FILE
-"""
-
-def _fuchsia_product_size_check_impl(ctx):
- images_out = ctx.attr.product_image[FuchsiaProductImageInfo].images_out
- ffx_tool = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"].ffx
-
- size_file = ctx.actions.declare_file(ctx.label.name + "_size_summary")
- ctx.actions.run_shell(
- inputs = ctx.files.product_image + [ffx_tool],
- outputs = [size_file],
- command = _SIZE_CHECKER_RUNNER_SH,
- env = {
- "FFX": ffx_tool.path,
- "IMAGES_PATH": images_out.path + "/images.json",
- "SIZE_FILE": size_file.path,
- },
- progress_message = "Size checking for %s" % ctx.label.name,
- )
- deps = [size_file]
-
- return [DefaultInfo(files = depset(direct = deps))]
-
-fuchsia_product_size_check = rule(
- doc = """Create a size summary of an image.""",
- implementation = _fuchsia_product_size_check_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "product_image": attr.label(
- doc = "fuchsia_product_image target to check size",
- providers = [FuchsiaProductImageInfo],
- mandatory = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_scrutiny_config.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_scrutiny_config.bzl
deleted file mode 100644
index 643316f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_scrutiny_config.bzl
+++ /dev/null
@@ -1,64 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaScrutinyConfigInfo")
-
-def _fuchsia_scrutiny_config_impl(ctx):
- return [
- FuchsiaScrutinyConfigInfo(
- bootfs_files = ctx.files.bootfs_files,
- bootfs_packages = ctx.files.bootfs_packages,
- kernel_cmdline = ctx.files.kernel_cmdline,
- routes_config_golden = ctx.file.routes_config_golden,
- component_resolver_allowlist = ctx.file.component_resolver_allowlist,
- component_route_exceptions = ctx.files.component_route_exceptions,
- component_tree_config = ctx.file.component_tree_config,
- base_packages = ctx.file.base_packages,
- structured_config_policy = ctx.file.structured_config_policy,
- ),
- ]
-
-fuchsia_scrutiny_config = rule(
- doc = """Generates a set of scrutiny configs.""",
- implementation = _fuchsia_scrutiny_config_impl,
- provides = [FuchsiaScrutinyConfigInfo],
- attrs = {
- "bootfs_files": attr.label_list(
- doc = "Set of files expected in bootfs",
- allow_files = True,
- ),
- "bootfs_packages": attr.label_list(
- doc = "Set of packages expected in bootfs",
- allow_files = True,
- ),
- "kernel_cmdline": attr.label_list(
- doc = "Set of cmdline args expected to be passed to the kernel",
- allow_files = True,
- ),
- "routes_config_golden": attr.label(
- doc = "Config file for route resources validation",
- allow_single_file = True,
- ),
- "component_resolver_allowlist": attr.label(
- doc = "Allowlist of components that can be resolved using privileged component resolvers",
- allow_single_file = True,
- ),
- "component_route_exceptions": attr.label_list(
- doc = "Allowlist of all capability routes that are exempt from route checking",
- allow_files = True,
- ),
- "component_tree_config": attr.label(
- doc = "Tree of expected component routes",
- allow_single_file = True,
- ),
- "base_packages": attr.label(
- doc = "Set of base packages expected in the fvm",
- allow_single_file = True,
- ),
- "structured_config_policy": attr.label(
- doc = "File describing the policy of structured config",
- allow_single_file = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_vbmeta.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_vbmeta.bzl
deleted file mode 100644
index 764c815..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_vbmeta.bzl
+++ /dev/null
@@ -1,36 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaVbmetaInfo")
-
-def _fuchsia_vbmeta_impl(ctx):
- return [
- FuchsiaVbmetaInfo(
- vbmeta_name = ctx.attr.vbmeta_name,
- key = ctx.file.key,
- key_metadata = ctx.file.key_metadata,
- ),
- ]
-
-fuchsia_vbmeta = rule(
- doc = """Generates a fuchsia vbmeta image.""",
- implementation = _fuchsia_vbmeta_impl,
- provides = [FuchsiaVbmetaInfo],
- attrs = {
- "vbmeta_name": attr.string(
- doc = "Name of vbmeta image appeared in image configuration",
- default = "fuchsia",
- ),
- "key": attr.label(
- doc = "the key for signing VBMeta.",
- allow_single_file = True,
- default = None,
- ),
- "key_metadata": attr.label(
- doc = "key metadata to add to the VBMeta.",
- allow_single_file = True,
- default = None,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_zbi.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_zbi.bzl
deleted file mode 100644
index d725e5a..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/fuchsia_zbi.bzl
+++ /dev/null
@@ -1,47 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaZbiInfo")
-
-# Define Zbi compression format
-ZBI_COMPRESSION = struct(
- ZSTD_MAX = "zstd.max",
- ZSTD = "zstd",
-)
-
-def _fuchsia_zbi_impl(ctx):
- return [
- FuchsiaZbiInfo(
- zbi_name = ctx.attr.zbi_name,
- compression = ctx.attr.compression,
- post_processing_script = ctx.file.post_processing_script,
- post_processing_args = ctx.attr.post_processing_args,
- ),
- ]
-
-fuchsia_zbi = rule(
- doc = """Generates a fuchsia zbi image.""",
- implementation = _fuchsia_zbi_impl,
- provides = [FuchsiaZbiInfo],
- attrs = {
- "zbi_name": attr.string(
- doc = "Name of zbi image appeared in image configuration",
- default = "fuchsia",
- ),
- "compression": attr.string(
- doc = "Zbi compression format",
- default = "zstd",
- values = [ZBI_COMPRESSION.ZSTD_MAX, ZBI_COMPRESSION.ZSTD],
- ),
- "post_processing_script": attr.label(
- doc = "Post procesing script",
- allow_single_file = True,
- default = None,
- ),
- "post_processing_args": attr.string_list(
- doc = "Args needed by post processing script",
- default = [],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/assembly/providers.bzl b/bazel_rules_fuchsia/fuchsia/private/assembly/providers.bzl
deleted file mode 100644
index c247e33..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/assembly/providers.bzl
+++ /dev/null
@@ -1,222 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Assembly related Providers."""
-
-load("@rules_fuchsia//fuchsia/private:providers.bzl", _FuchsiaProductBundleInfo = "FuchsiaProductBundleInfo")
-
-FuchsiaAssembledPackageInfo = provider(
- "Packages that can be included into a product. It consists of the package and the corresponding config data.",
- fields = {
- "package": "The base package",
- "configs": "A list of configs that is attached to packages",
- },
-)
-
-FuchsiaConfigData = provider(
- "The config data which is used in assembly.",
- fields = {
- "source": "Config file on host",
- "destination": "A String indicating the path to find the file in the package on the target",
- },
-)
-
-FuchsiaIdentityConfigInfo = provider(
- doc = "Platform configuration options for the identity area.",
- fields = {
- "password_pinweaver": "Whether the pinweaver protocol should be enabled in `password_authenticator` on supported boards. Pinweaver will always be disabled if the board does not support the protocol.",
- },
-)
-
-FuchsiaInputConfigInfo = provider(
- doc = "Platform configuration options for the input area.",
- fields = {
- "idle_threshold_minutes": "How much time has passed since the last user input activity for the system to become idle.",
- "supported_input_devices": "The relevant input device bindings from which to install appropriate input handlers.",
- },
-)
-
-FuchsiaDevelopmentSupportConfigInfo = provider(
- doc = "Platform configuration options for the development_support area.",
- fields = {
- "enabled": "A bool value whether development_support is enabled",
- },
-)
-
-FuchsiaStarnixConfigInfo = provider(
- doc = "Platform starnix options for the starnix area.",
- fields = {
- "enabled": "Whether starnix support should be included",
- },
-)
-
-FuchsiaConnectivityConfigInfo = provider(
- doc = "Platform configuration options for the connectivity area.",
- fields = {
- "wlan": "WLAN sub configuration",
- },
-)
-
-FuchsiaConnectivityWlanConfigInfo = provider(
- doc = "Platform configuration options for the connectivity area wlan field.",
- fields = {
- "legacy_privacy_support": "A bool value for legacy_privacy_support of wlan",
- "include_wlan_aibs": "A bool value for include_wlan_aibs of wlan",
- },
-)
-
-FuchsiaDiagnosticsConfigInfo = provider(
- doc = "Platform configuration options for the diagnostics area.",
- fields = {
- "archivist": "Archivist configuration selection",
- },
-)
-
-FuchsiaProductConfigInfo = provider(
- doc = "A product-info used to containing the product_config.json and deps.",
- fields = {
- "product_config": "The JSON product configuration file.",
- },
-)
-
-FuchsiaBoardConfigInfo = provider(
- doc = "A board-info used to containing the board_config.json and deps.",
- fields = {
- "board_config": "The JSON board configuration file.",
- },
-)
-
-FuchsiaAssemblyConfigInfo = provider(
- doc = "Private provider that includes a single JSON configuration file.",
- fields = {
- "config": "JSON configuration file",
- },
-)
-
-FuchsiaProductAssemblyBundleInfo = provider(
- doc = """
-A bundle of files used by product assembly.
-This should only be provided by the single exported target of a
-fuchsia_product_assembly_bundle repository.
-""",
- fields = {
- "dir": "Path to the bundle directory",
- "files": "All files contained in the bundle",
- },
-)
-
-FuchsiaZbiInfo = provider(
- doc = """An Image info for Zbi.""",
- fields = {
- "zbi_name": "Name of zbi image appeared in image configuration",
- "compression": "Zbi compression format",
- "post_processing_script": "Post procesing script",
- "post_processing_args": "Args needed by post processing script",
- },
-)
-
-FuchsiaVbmetaInfo = provider(
- doc = """An Image info for Vbmeta.""",
- fields = {
- "vbmeta_name": "Name of vbmeta image appeared in image configuration",
- "key": "the key for signing VBMeta.",
- "key_metadata": "key metadata to add to the VBMeta.",
- },
-)
-
-FuchsiaFsBlobFsInfo = provider(
- doc = """A BlobFs filesystem.""",
- fields = {
- "blobfs_name": "Name of filesystem",
- "blobfs_info": "Json of Blob FS information",
- },
-)
-
-FuchsiaFsMinFsInfo = provider(
- doc = """A MinFs filesystem.""",
- fields = {
- "minfs_name": "Name of filesystem",
- "minfs_info": "Json of Min FS information",
- },
-)
-
-FuchsiaFsEmptyDataInfo = provider(
- doc = """An Empty MinFs filesystem.""",
- fields = {
- "empty_data_name": "Name of filesystem",
- },
-)
-
-FuchsiaFsEmptyAccountInfo = provider(
- doc = """An Empty Account filesystem.""",
- fields = {
- "empty_account_name": "Name of filesystem",
- },
-)
-
-FuchsiaFsReservedInfo = provider(
- doc = """A Reserved filesystem.""",
- fields = {
- "reserved_name": "Name of filesystem",
- "reserved_info": "Json of Reserved FS information",
- },
-)
-
-FuchsiaFVMStandardInfo = provider(
- doc = "A fvm with no modification.",
- fields = {
- "fvm_standard_name": "Name of fvm file",
- "filesystems": "Filesystems to use",
- "fvm_info": "Json of FVM information",
- },
-)
-
-FuchsiaFVMSparseInfo = provider(
- doc = "A fvm that is compressed sparse.",
- fields = {
- "fvm_sparse_name": "Name of fvm file",
- "filesystems": "Filesystems to use",
- "fvm_info": "Json of FVM information",
- },
-)
-
-FuchsiaFVMNandInfo = provider(
- doc = "A FVM prepared for a Nand partition.",
- fields = {
- "fvm_nand_name": "Name of fvm file",
- "filesystems": "Filesystems to use",
- "fvm_info": "Json of FVM information",
- },
-)
-
-FuchsiaProductImageInfo = provider(
- doc = "Info needed to pave a Fuchsia image",
- fields = {
- "images_out": "images out directory",
- },
-)
-
-FuchsiaProductBundleInfo = _FuchsiaProductBundleInfo
-
-FuchsiaPartitionInfo = provider(
- doc = "Mapping of images to partitions.",
- fields = {
- "partition": "partition in dict",
- },
-)
-
-FuchsiaScrutinyConfigInfo = provider(
- doc = "A set of scrutiny configs.",
- fields = {
- "bootfs_files": "Set of files expected in bootfs",
- "bootfs_packages": "Set of packages expected in bootfs",
- "kernel_cmdline": "Set of cmdline args expected to be passed to the kernel",
- "component_tree_config": "Tree of expected component routes",
- "routes_config_golden": "Config file for route resources validation",
- "component_resolver_allowlist": "Allowlist of components that can be resolved using privileged component resolvers",
- "component_route_exceptions": "Allowlist of all capability routes that are exempt from route checking",
- "base_packages": "Set of base packages expected in the fvm",
- "structured_config_policy": "File describing the policy of structured config",
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/compilation_database.bzl b/bazel_rules_fuchsia/fuchsia/private/compilation_database.bzl
deleted file mode 100644
index 179d03a..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/compilation_database.bzl
+++ /dev/null
@@ -1,230 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
-load(
- "@bazel_tools//tools/build_defs/cc:action_names.bzl",
- "CPP_COMPILE_ACTION_NAME",
- "C_COMPILE_ACTION_NAME",
-)
-
-_CC_RULES = [
- "cc_library",
- "cc_binary",
- "cc_test",
- "cc_inc_library",
- "cc_proto_library",
-]
-
-_CPP_HEADER_EXT = [
- "hpp",
- "hxx",
- "hh",
- "ipp",
-]
-
-_HEADER_EXT = _CPP_HEADER_EXT + ["h"]
-
-_CPP_SRC_EXT = [
- "cpp",
- "cxx",
- "cc",
-]
-
-_CPP_EXT = _CPP_SRC_EXT + _CPP_HEADER_EXT
-
-# Placeholder for exec root directory.
-_EXEC_ROOT_MARKER = "__EXEC_ROOT__"
-
-# Assume C++ if all files are headers or there is a c++ file.
-def _is_cpp_target(srcs):
- if any([src.extension in _CPP_EXT for src in srcs]):
- return True
- if all([src.extension in _HEADER_EXT for src in srcs]):
- return True
- return False
-
-def _get_sources(ctx, target):
- srcs = []
- if hasattr(ctx.rule.attr, "srcs"):
- srcs += [f for src in ctx.rule.attr.srcs for f in src.files.to_list()]
- if hasattr(ctx.rule.attr, "hdrs"):
- srcs += [f for src in ctx.rule.attr.hdrs for f in src.files.to_list()]
-
- return srcs
-
-def _add_compile_flags(options, flag, args):
- for arg in args.to_list():
- if len(arg) == 0:
- arg = "."
- options.append("{} {}".format(flag, arg))
-
-# Get compilation options from the CompilationContext from CcInfo
-# https://docs.bazel.build/versions/main/skylark/lib/CcInfo.html
-def _get_compile_flags(dep):
- options = []
- compilation_context = dep[CcInfo].compilation_context
-
- # ignore headers and validation_artifacts.
- _add_compile_flags(options, "-I", compilation_context.includes)
- _add_compile_flags(options, "-isystem", compilation_context.system_includes)
- _add_compile_flags(options, "-iquote", compilation_context.quote_includes)
- _add_compile_flags(options, "-F", compilation_context.framework_includes)
- _add_compile_flags(options, "-D", compilation_context.defines)
- _add_compile_flags(options, "-D", compilation_context.local_defines)
-
- return options
-
-CompilationAspectInfo = provider(
- doc = "A private provider to pass information from a package build to archive.",
- fields = {
- "compilation_db": "compilation database",
- },
-)
-
-# Returns the command lines to compile all the c/c++ source files for the given target.
-def _cc_compile_commands(ctx, target, feature_configuration, cc_toolchain):
- compile_flags = _get_compile_flags(target)
-
- #Assume C++ code
- srcs = _get_sources(ctx, target)
-
- if _is_cpp_target(srcs):
- compile_variables = cc_common.create_compile_variables(
- feature_configuration = feature_configuration,
- cc_toolchain = cc_toolchain,
- user_compile_flags = ctx.fragments.cpp.cxxopts +
- ctx.fragments.cpp.copts,
- add_legacy_cxx_options = True,
- )
- action_name = CPP_COMPILE_ACTION_NAME
- else:
- compile_variables = cc_common.create_compile_variables(
- feature_configuration = feature_configuration,
- cc_toolchain = cc_toolchain,
- user_compile_flags = ctx.fragments.cpp.copts,
- )
- action_name = C_COMPILE_ACTION_NAME
-
- compiler_options = cc_common.get_memory_inefficient_command_line(
- feature_configuration = feature_configuration,
- action_name = action_name,
- variables = compile_variables,
- )
-
- if hasattr(ctx.rule.attr, "copts"):
- compile_flags.extend(ctx.rule.attr.copts)
-
- compiler_info = str(
- cc_common.get_tool_for_action(
- feature_configuration = feature_configuration,
- action_name = action_name,
- ),
- )
- cmdline_list = [compiler_info]
- cmdline_list.extend(compiler_options)
- cmdline_list.extend(compile_flags)
- cmdline = " ".join(cmdline_list)
-
- compile_commands = []
- for src in srcs:
- compile_commands.append(struct(
- cmdline = cmdline + " -c " + src.path,
- src = src,
- ))
- return compile_commands
-
-# Returns a list of compilation_db object entries for the given target.
-def _build_compilation_db(target, ctx):
- compilation_db = []
- cc_toolchain = find_cpp_toolchain(ctx)
- feature_configuration = cc_common.configure_features(
- ctx = ctx,
- cc_toolchain = cc_toolchain,
- requested_features = ctx.features,
- unsupported_features = ctx.disabled_features,
- )
-
- if ctx.rule.kind in _CC_RULES:
- compile_commands = _cc_compile_commands(ctx, target, feature_configuration, cc_toolchain)
- else:
- return []
-
- for compile_command in compile_commands:
- compilation_db.append(
- struct(
- command = compile_command.cmdline,
- directory = _EXEC_ROOT_MARKER,
- file = compile_command.src.path,
- ),
- )
-
- return compilation_db
-
-def _compilation_db_aspect_impl(target, ctx):
- transitive_compilation_db = []
-
- # Applies the aspect to the targets in the deps attribute, if present.
- if hasattr(ctx.rule.attr, "deps"):
- for dep in ctx.rule.attr.deps:
- transitive_compilation_db.append(dep[CompilationAspectInfo].compilation_db)
-
- if hasattr(ctx.rule.attr, "content"):
- for dep in ctx.rule.attr.content:
- if CompilationAspectInfo in dep:
- transitive_compilation_db.append(dep[CompilationAspectInfo].compilation_db)
-
- compilation_db = depset(
- _build_compilation_db(target, ctx),
- transitive = transitive_compilation_db,
- )
-
- return [CompilationAspectInfo(compilation_db = compilation_db)]
-
-compilation_db_aspect = aspect(
- implementation = _compilation_db_aspect_impl,
- attr_aspects = ["deps", "content"],
- attrs = {
- "_cc_toolchain": attr.label(
- default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
- ),
- },
- fragments = ["cpp"],
- toolchains = ["@bazel_tools//tools/cpp:toolchain_type"],
-)
-
-def _compilation_db_rule_impl(ctx):
- compilation_db = []
- for dep in ctx.attr.deps:
- compilation_db.append(dep[CompilationAspectInfo].compilation_db)
-
- compilation_db = depset(transitive = compilation_db)
-
- exec_root = ctx.attr.output_base + "/execroot/" + ctx.workspace_name
-
- content = json.encode(compilation_db.to_list())
- content = content.replace(_EXEC_ROOT_MARKER, exec_root)
-
- out = ctx.actions.declare_file(ctx.attr.filename.name)
- ctx.actions.write(output = ctx.outputs.filename, content = content)
-
-_clangd_compilation_database = rule(
- implementation = _compilation_db_rule_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "output_base": attr.string(
- default = "__OUTPUT_BASE__",
- doc = ("Output Bazel directory to store the compilation database"),
- ),
- "deps": attr.label_list(aspects = [compilation_db_aspect]),
- "filename": attr.output(),
- },
-)
-
-# TODO(fxbug.dev/92380): Revisit the compilation database implementation after a review of alternatives
-def clangd_compilation_database(**kwargs):
- _clangd_compilation_database(
- filename = kwargs.pop("filename", "compile_commands.json"),
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/debug_info.bzl b/bazel_rules_fuchsia/fuchsia/private/debug_info.bzl
deleted file mode 100644
index b4bae01..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/debug_info.bzl
+++ /dev/null
@@ -1,84 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-def _print_debug_info_impl(ctx):
- sdk = ctx.toolchains["//fuchsia:toolchain"]
-
- executable_file = ctx.actions.declare_file(ctx.label.name + "_dump.sh")
- content = """#!/bin/bash
- echo "----------------------------------------------------------"
- echo "========================================================="
- echo "*** SDK Version:"
- echo "========================================================="
- sdk_version=$({ffx} sdk version)
- echo "sdk_version: $({ffx} sdk version)"
- (
- # Check to see if the user has an sdk-integration repo so
- # we can grab the git hash. This will not be needed once we
- # release the rules with the core sdk.
- if cd "$BUILD_WORKSPACE_DIRECTORY/third_party/sdk-integration"; then
- git_revision=$(git rev-parse HEAD)
- echo "sdk-integration git rev: $git_revision"
- else
- echo "Cannot find an sdk-integration repository"
- fi
- )
- echo
-
- echo "========================================================="
- echo "*** Output from uname -v:"
- echo "========================================================="
- uname -v
- echo
-
- echo "========================================================="
- echo "*** Output from ffx version -v:"
- echo "========================================================="
- "{ffx}" version -v
- echo
-
- echo "========================================================="
- echo "*** Output from ffx doctor --no-config:"
- echo "========================================================="
- "{ffx}" doctor --no-config
- echo
-
- echo "========================================================="
- echo "*** Output from clang --version:"
- echo "========================================================="
- if [[ -x "{clang}" ]]; then
- "{clang}" --version
- else
- echo "Cannot find a suitable clang binary: {clang}"
- fi
-
- echo "----------------------------------------------------------"
- """.format(
- ffx = sdk.ffx.short_path,
- clang = ctx.executable._clang_bin.short_path,
- )
-
- ctx.actions.write(
- output = executable_file,
- content = content,
- is_executable = True,
- )
-
- runfiles = ctx.runfiles(files = [sdk.ffx, ctx.executable._clang_bin])
- return [DefaultInfo(executable = executable_file, runfiles = runfiles)]
-
-print_debug_info = rule(
- doc = """ Creates an action which gathers debug information and prints it.""",
- implementation = _print_debug_info_impl,
- toolchains = ["//fuchsia:toolchain"],
- attrs = {
- "_clang_bin": attr.label(
- default = "@fuchsia_clang//:bin/clang",
- executable = True,
- cfg = "exec",
- allow_single_file = True,
- ),
- },
- executable = True,
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/flags.bzl b/bazel_rules_fuchsia/fuchsia/private/flags.bzl
deleted file mode 100644
index f505698..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/flags.bzl
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load("//fuchsia/private:providers.bzl", "FuchsiaPackageRepoPathInfo")
-
-def _package_repo_path_flag_impl(ctx):
- path = ctx.build_setting_value
- return FuchsiaPackageRepoPathInfo(path = path)
-
-package_repo_path_flag = rule(
- implementation = _package_repo_path_flag_impl,
- build_setting = config.string(flag = True),
- doc = """
- A string-typed build setting that can be set on the command line to
- specify the path to the package repository.
- """,
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_bind_cc_library.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_bind_cc_library.bzl
deleted file mode 100644
index 2e428a8..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_bind_cc_library.bzl
+++ /dev/null
@@ -1,87 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""A cc_library generated from a bind library."""
-
-load(":providers.bzl", "FuchsiaBindLibraryInfo")
-
-def _codegen_impl(context):
- sdk = context.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- bindc = sdk.bindc
- base_path = context.attr.name
- name = context.attr.library[FuchsiaBindLibraryInfo].name.replace(".", "/").replace("_bindlib", "")
- bind_source = context.attr.library[DefaultInfo].files.to_list()[0]
-
- # This declaration is needed in order to get access to the full path.
- root = context.actions.declare_directory(base_path)
-
- # The generated header fie.
- header_relative = "/bind/" + name + "/cpp" + "/bind.h"
- headers = [context.actions.declare_file(base_path + header_relative)]
-
- outputs = [root] + headers
- context.actions.run(
- executable = bindc,
- arguments = [
- "generate-cpp",
- "--lint",
- "--output",
- root.path + header_relative,
- bind_source.path,
- ],
- inputs = [
- bind_source,
- ],
- outputs = outputs,
- mnemonic = "BindcGenCc",
- )
-
- return [
- DefaultInfo(files = depset(headers)),
- ]
-
-# Runs bindc to produce the header file with the constants for the bind_library.
-_codegen = rule(
- implementation = _codegen_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- # Files must be generated in genfiles in order for the header to be included
- # anywhere.
- output_to_genfiles = True,
- attrs = {
- "library": attr.label(
- doc = "The bind library to generate code for",
- mandatory = True,
- allow_files = False,
- providers = [FuchsiaBindLibraryInfo],
- ),
- },
-)
-
-def fuchsia_bind_cc_library(name, library, deps = [], tags = [], **kwargs):
- """Generates a cc_library() for the given fuchsia_bind_library().
-
- Args:
- name: Target name. Required.
- library: fuchsia_bind_library() target to generate the code for. Required.
- deps: Additional dependencies.
- tags: Optional tags.
- **kwargs: Remaining args.
- """
- gen_name = "%s_codegen" % name
- _codegen(
- name = gen_name,
- library = library,
- )
-
- native.cc_library(
- name = name,
- hdrs = [
- ":%s" % gen_name,
- ],
- # This is necessary in order to locate generated headers.
- strip_include_prefix = gen_name,
- deps = deps,
- tags = tags,
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_bind_library.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_bind_library.bzl
deleted file mode 100644
index 86ffc05..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_bind_library.bzl
+++ /dev/null
@@ -1,47 +0,0 @@
-"""Implementation of bind_library rule"""
-
-# A Bind library.
-#
-# Parameters
-#
-# srcs
-# List of source files.
-#
-# deps
-# List of other bind_library targets included by the library.
-
-load(":providers.bzl", "FuchsiaBindLibraryInfo")
-
-def _get_transitive_srcs(srcs, deps):
- return depset(
- srcs,
- transitive = [dep[FuchsiaBindLibraryInfo].transitive_sources for dep in deps],
- )
-
-def _bind_library_impl(context):
- # In-tree bind libraries have exactly 1 source file.
- if len(context.files.srcs) != 1:
- fail("There must be exactly 1 item in 'srcs'.")
-
- trans_srcs = _get_transitive_srcs(context.files.srcs, context.attr.deps)
- return [
- FuchsiaBindLibraryInfo(name = context.attr.name, transitive_sources = trans_srcs),
- DefaultInfo(files = depset(context.files.srcs)),
- ]
-
-fuchsia_bind_library = rule(
- implementation = _bind_library_impl,
- attrs = {
- "srcs": attr.label_list(
- doc = "The list of bind library source files",
- mandatory = True,
- allow_files = True,
- allow_empty = False,
- ),
- "deps": attr.label_list(
- doc = "The list of bind libraries this library depends on",
- mandatory = False,
- providers = [FuchsiaBindLibraryInfo],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_cc.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_cc.bzl
deleted file mode 100644
index 243feaa..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_cc.bzl
+++ /dev/null
@@ -1,407 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Fuchsia cc primitives.
-
-Drop in replacements for cc_binary and cc_test:
- - fuchsia_cc_binary
- - fuchsia_cc_test
-
-cc_binary & cc_test wrappers:
- - fuchsia_wrap_cc_binary
- - fuchsia_wrap_cc_test
-"""
-
-load(":utils.bzl", "forward_providers", "get_runfiles", "is_lib", "make_resource_struct", "rule_variant", "rule_variants")
-load(":fuchsia_select.bzl", "if_fuchsia")
-load(":fuchsia_component.bzl", "fuchsia_test_component")
-load(":fuchsia_component_manifest.bzl", "fuchsia_component_manifest")
-load(
- ":providers.bzl",
- "FuchsiaComponentInfo",
- "FuchsiaDebugSymbolInfo",
- "FuchsiaPackageResourcesInfo",
- "FuchsiaUnitTestComponentInfo",
-)
-
-KNOWN_PROVIDERS = [
- CcInfo,
- # This provider is generated by cc_binary/cc_test, but there's no way to
- # load it.
- # CcLauncherInfo,
- DebugPackageInfo,
- FuchsiaDebugSymbolInfo,
- FuchsiaPackageResourcesInfo,
- InstrumentedFilesInfo,
- OutputGroupInfo,
-]
-
-_invalid_deps_message = """Missing or mismatched exact_cc_%s_deps.
-Please factor out the deps of `%s` and pass them into **both targets**.
-If there are no deps, assign an empty list and pass into into both."""
-
-def _fuchsia_cc_impl(ctx):
- # Expect exactly one binary to be generated by the native cc_* rule.
- native_outputs = ctx.attr.native_target.files.to_list()
- if len(native_outputs) != 1:
- fail("Expected exactly 1 native output for %s, got %s" % (ctx.attr.native_target, native_outputs))
-
- resources = [
- # The binary generated by the native cc_* rule.
- make_resource_struct(src = native_outputs[0], dest = "bin/" + ctx.attr.bin_name),
- ]
- for data in ctx.attr.data:
- resources.extend(data[FuchsiaPackageResourcesInfo].resources)
-
- # Collect files the native target, deps, and implicit libs.
- dep_files = [file for dep in ctx.attr.deps + [
- implicit
- for implicit in ctx.attr.implicit_deps
- if implicit not in ctx.attr.deps
- ] for file in dep.files.to_list()] + get_runfiles(ctx.attr.native_target)
-
- # Add libraries from above files as resources.
- resources += [
- make_resource_struct(src = file, dest = "lib/" + file.basename)
- for file in dep_files
- if is_lib(file)
- ]
-
- # Forward CC providers along with metadata for packaging.
- return forward_providers(
- ctx,
- ctx.attr.native_target,
- rename_executable = ctx.attr._variant != "test" and ctx.attr.bin_name,
- *KNOWN_PROVIDERS
- ) + [
- ctx.attr.clang_debug_symbols[FuchsiaDebugSymbolInfo],
- FuchsiaPackageResourcesInfo(resources = resources),
- ]
-
-_fuchsia_cc_binary, _fuchsia_cc_test = rule_variants(
- variants = ("executable", "test"),
- implementation = _fuchsia_cc_impl,
- doc = """Attaches fuchsia-specific metadata to native cc_* targets.
-
- This allows them to be directly included in fuchsia_component.
- """,
- attrs = {
- "bin_name": attr.string(
- doc = "The name of the executable to place under bin/.",
- mandatory = True,
- ),
- "native_target": attr.label(
- doc = "The underlying cc_* target.",
- mandatory = True,
- providers = [[CcInfo, DefaultInfo]],
- ),
- "clang_debug_symbols": attr.label(
- doc = "Clang debug symbols.",
- mandatory = True,
- providers = [FuchsiaDebugSymbolInfo],
- ),
- "deps": attr.label_list(
- doc = """The exact list of dependencies dep-ed on by native_target.
-
- We need these because we can't rely on `cc_binary`'s DefaultInfo
- [run]files (Bazel does not handle static libraries correctly.)
- See https://github.com/bazelbuild/bazel/issues/1920.
-
- Failure to provide the *exact list* of dependencies may result in a
- runtime crash.
- """,
- providers = [[CcInfo, DefaultInfo]],
- ),
- "implicit_deps": attr.label_list(
- doc = """Implicit resources/libraries to include within the resulting package.""",
- ),
- "data": attr.label_list(
- doc = "Packaged files needed by this target at runtime.",
- providers = [FuchsiaPackageResourcesInfo],
- ),
- },
-)
-
-# fuchsia_cc_binary build rules.
-def fuchsia_wrap_cc_binary(
- name = None,
- bin_name = None,
- cc_binary = None,
- exact_cc_binary_deps = None,
- sdk_root_label = "@fuchsia_sdk",
- clang_root_label = "@fuchsia_clang",
- **kwargs):
- """Wrap a native cc_binary.
-
- The resulting target can be used as a dep in fuchsia_component.
-
- Args:
- name: This target name.
- bin_name: The filename to place under bin/. Defaults to name.
- cc_binary: The existing cc_binary's target name.
- exact_cc_binary_deps: The existing cc_binary's deps. This **ALWAYS MUST BE**
- identical to cc_binary's deps to prevent runtime crashes.
- We recommend factoring out cc_binary's deps and then referencing
- them in cc_binary as well as fuchsia_wrap_cc_binary.
- sdk_root_label: Optionally override the root label of the fuchsia sdk repo.
- clang_root_label: Optionally override the root label of the fuchsia clang repo.
- **kwargs: Arguments to forward to the fuchsia cc_binary wrapper.
- """
- if exact_cc_binary_deps == None:
- fail(_invalid_deps_message % ("binary", cc_binary))
-
- _fuchsia_cc_binary(
- name = name,
- bin_name = bin_name if bin_name != None else name,
- native_target = cc_binary,
- clang_debug_symbols = "%s//:debug_symbols" % clang_root_label,
- deps = exact_cc_binary_deps,
- implicit_deps = ["%s//pkg/fdio" % sdk_root_label],
- data = [
- "%s//pkg/sysroot:dist" % sdk_root_label,
- "%s//:dist" % clang_root_label,
- "%s//:runtime" % clang_root_label,
- ],
- **kwargs
- )
-
-def fuchsia_cc_binary(
- name = None,
- sdk_root_label = "@fuchsia_sdk",
- clang_root_label = "@fuchsia_clang",
- tags = None,
- visibility = None,
- **cc_binary_kwargs):
- """A fuchsia-specific cc_binary drop-in replacement.
-
- The resulting target can be used as a dep in fuchsia_component.
-
- Args:
- name: The target name.
- sdk_root_label: Optionally override the root label of the fuchsia sdk repo.
- clang_root_label: Optionally override the root label of the fuchsia clang repo.
- tags: The tags of all generated targets.
- visibility: The visibility of all generated targets.
- **cc_binary_kwargs: Arguments to forward to `cc_binary`.
- """
- native.cc_binary(
- name = "_%s_native" % name,
- tags = tags,
- visibility = visibility,
- **cc_binary_kwargs
- )
- native.alias(
- name = "%s_native" % name,
- actual = "_%s_native" % name,
- tags = tags,
- visibility = visibility,
- deprecation = "fuchsia_cc_binary supports direct execution now. Please use `:%s` instead." % name,
- )
- fuchsia_wrap_cc_binary(
- name = name,
- cc_binary = "_%s_native" % name,
- exact_cc_binary_deps = cc_binary_kwargs["deps"] if "deps" in cc_binary_kwargs else [],
- sdk_root_label = sdk_root_label,
- clang_root_label = clang_root_label,
- tags = tags,
- visibility = visibility,
- )
-
-# fuchsia_cc_test build rules.
-def _fuchsia_cc_test_manifest_impl(ctx):
- # Detect googletest.
- is_gtest = False
- for dep in ctx.attr.deps:
- if dep.label.workspace_name == ctx.attr.googletest.label.workspace_name:
- is_gtest = True
- break
-
- # Write cml.
- generated_cml = ctx.actions.declare_file("%s.cml" % ctx.label.name)
- ctx.actions.expand_template(
- template = ctx.attr._template_file.files.to_list()[0],
- output = generated_cml,
- substitutions = {
- "{{RUNNER}}": "gtest_runner" if is_gtest else "elf_test_runner",
- "{{BINARY}}": ctx.attr.test_binary_name,
- },
- )
-
- return [
- DefaultInfo(files = depset([generated_cml])),
- ]
-
-_fuchsia_cc_test_manifest = rule(
- implementation = _fuchsia_cc_test_manifest_impl,
- doc = """Generates a stub cml file for a given cc_test-backed _fuchsia_cc.
-
- Detects whether gtest is included as a dependency. If it is, the cml file
- will use gtest_runner. Otherwise it will use the elf_test_runner.
- """,
- attrs = {
- "test_binary_name": attr.string(
- doc = "The test binary's name.",
- mandatory = True,
- ),
- "deps": attr.label_list(
- doc = "The same deps passed into _fuchsia_cc.",
- mandatory = True,
- providers = [[CcInfo, DefaultInfo]],
- ),
- "googletest": attr.label(
- doc = "Any googletest label.",
- allow_single_file = True,
- mandatory = True,
- ),
- "_template_file": attr.label(
- doc = "The template cml file.",
- default = "//fuchsia/private:templates/cc_test_manifest.cml",
- allow_single_file = True,
- ),
- },
-)
-
-def _add_component_info_for_unit_test_impl(ctx):
- return forward_providers(ctx, ctx.attr.base) + ([
- FuchsiaUnitTestComponentInfo(test_component = ctx.attr.generated_component),
- ] if ctx.attr.generated_component else [])
-
-_add_component_info_for_unit_test = rule_variant(
- variant = "test",
- implementation = _add_component_info_for_unit_test_impl,
- doc = """Provides FuchsiaUnitTestComponentInfo on top of _fuchsia_cc providers.""",
- attrs = {
- "base": attr.label(
- doc = "The base _fuchsia_cc target.",
- mandatory = True,
- providers = [[CcInfo, FuchsiaPackageResourcesInfo]],
- ),
- "generated_component": attr.label(
- doc = "The autogenerated test component.",
- providers = [FuchsiaComponentInfo],
- ),
- },
-)
-
-def fuchsia_wrap_cc_test(
- name = None,
- cc_test = None,
- exact_cc_test_deps = None,
- sdk_root_label = "@fuchsia_sdk",
- clang_root_label = "@fuchsia_clang",
- googletest_root_label = "@com_google_googletest",
- **kwargs):
- """Wrap a native cc_test.
-
- The resulting target can be used as a dep in fuchsia_component.
-
- Args:
- name: This target name.
- cc_test: The existing cc_test's target name.
- exact_cc_test_deps: The existing cc_test's deps. This **ALWAYS MUST BE**
- identical to cc_test's deps to prevent runtime crashes.
- We recommend factoring out cc_test's deps and then referencing
- them in cc_test as well as fuchsia_wrap_cc_test.
- sdk_root_label: Optionally override the root label of the fuchsia sdk repo.
- clang_root_label: Optionally override the root label of the fuchsia clang repo.
- googletest_root_label: Optionally override the root label of the googletest repo.
- **kwargs: Arguments to forward to the fuchsia cc_test wrapper.
- """
- if exact_cc_test_deps == None:
- fail(_invalid_deps_message % ("test", cc_test))
-
- _fuchsia_cc_test(
- name = "%s_native_cc" % name,
- bin_name = name,
- native_target = cc_test,
- clang_debug_symbols = "%s//:debug_symbols" % clang_root_label,
- deps = exact_cc_test_deps,
- implicit_deps = ["%s//pkg/fdio" % sdk_root_label],
- data = [
- "%s//pkg/sysroot:dist" % sdk_root_label,
- "%s//:dist" % clang_root_label,
- "%s//:runtime" % clang_root_label,
- ],
- **kwargs
- )
-
- _fuchsia_cc_test_manifest(
- name = "%s_autogen_cml" % name,
- test_binary_name = name,
- deps = exact_cc_test_deps,
- googletest = "%s//:BUILD.bazel" % googletest_root_label,
- **kwargs
- )
-
- # Generate a default component manifest.
- fuchsia_component_manifest(
- name = "%s_autogen_manifest" % name,
- component_name = name,
- src = ":%s_autogen_cml" % name,
- **kwargs
- )
-
- # Generate the default component.
- fuchsia_test_component(
- name = "%s_autogen_component" % name,
- content = {
- ":%s_autogen_manifest" % name: "meta/%s.cm" % name,
- },
- manifest = ":%s_autogen_manifest" % name,
- deps = [":%s_native_cc" % name],
- **kwargs
- )
-
- _add_component_info_for_unit_test(
- name = name,
- base = ":%s_native_cc" % name,
- generated_component = if_fuchsia(":%s_autogen_component" % name, if_not = None),
- testonly = True,
- **kwargs
- )
-
-def fuchsia_cc_test(
- name = None,
- sdk_root_label = "@fuchsia_sdk",
- clang_root_label = "@fuchsia_clang",
- googletest_root_label = "@com_google_googletest",
- tags = None,
- visibility = None,
- **cc_test_kwargs):
- """A fuchsia-specific cc_test drop-in replacement.
-
- The resulting target can be used as a dep in fuchsia_component.
-
- Args:
- name: The target name.
- sdk_root_label: Optionally override the root label of the fuchsia sdk repo.
- clang_root_label: Optionally override the root label of the fuchsia clang repo.
- googletest_root_label: Optionally override the root label of the googletest repo.
- tags: The tags of all generated targets.
- visibility: The visibility of all generated targets.
- **cc_test_kwargs: Arguments to forward to `cc_test`.
- """
- native.cc_test(
- name = "_%s_native" % name,
- tags = tags,
- visibility = visibility,
- **cc_test_kwargs
- )
- native.alias(
- name = "%s_native" % name,
- actual = "_%s_native" % name,
- tags = tags,
- visibility = visibility,
- deprecation = "fuchsia_cc_test supports direct execution now. Please use `:%s` instead." % name,
- )
- fuchsia_wrap_cc_test(
- name = name,
- cc_test = "_%s_native" % name,
- exact_cc_test_deps = cc_test_kwargs["deps"] if "deps" in cc_test_kwargs else [],
- sdk_root_label = sdk_root_label,
- clang_root_label = clang_root_label,
- googletest_root_label = googletest_root_label,
- tags = tags,
- visibility = visibility,
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_component.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_component.bzl
deleted file mode 100644
index 7ca4871..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_component.bzl
+++ /dev/null
@@ -1,160 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":fuchsia_debug_symbols.bzl", "collect_debug_symbols")
-load(":providers.bzl", "FuchsiaComponentInfo", "FuchsiaPackageResourcesInfo", "FuchsiaUnitTestComponentInfo")
-load(":utils.bzl", "make_resource_struct", "rule_variant", "rule_variants")
-
-def fuchsia_component(name, manifest, deps = None, **kwargs):
- """Creates a Fuchsia component that can be added to a package.
-
- Args:
- name: The target name.
- manifest: The component manifest file.
- deps: A list of targets that this component depends on.
- **kwargs: Extra attributes to forward to the build rule.
- """
- _fuchsia_component(
- name = name,
- manifest = manifest,
- deps = deps,
- is_driver = False,
- **kwargs
- )
-
-def fuchsia_test_component(name, manifest, deps = None, **kwargs):
- """Creates a Fuchsia component that can be added to a test package.
-
- Args:
- name: The target name.
- manifest: The component manifest file.
- deps: A list of targets that this component depends on.
- **kwargs: Extra attributes to forward to the build rule.
- """
- _fuchsia_component_test(
- name = name,
- manifest = manifest,
- deps = deps,
- is_driver = False,
- **kwargs
- )
-
-def fuchsia_driver_component(name, manifest, driver_lib, bind_bytecode, deps = None, **kwargs):
- """Creates a Fuchsia component that can be registered as a driver.
-
- Args:
- name: The target name.
- manifest: The component manifest file.
- driver_lib: The shared library that will be registered with the driver manager.
- This file will end up in /driver/<lib_name> and should match what is listed
- in the manifest. See https://fuchsia.dev/fuchsia-src/concepts/components/v2/driver_runner
- for more details.
- bind_bytecode: The driver bind bytecode needed for binding the driver.
- deps: A list of targets that this component depends on.
- **kwargs: Extra attributes to forward to the build rule.
- """
- _fuchsia_component(
- name = name,
- manifest = manifest,
- deps = deps,
- content = {
- driver_lib: "driver/",
- bind_bytecode: "meta/bind/",
- },
- is_driver = True,
- **kwargs
- )
-
-def _fuchsia_component_impl(ctx):
- component_name = ctx.attr.component_name or ctx.label.name
- manifest = ctx.file.manifest
-
- resources = []
- for dep in ctx.attr.deps:
- if FuchsiaPackageResourcesInfo in dep:
- resources += dep[FuchsiaPackageResourcesInfo].resources
- else:
- for mapping in dep[DefaultInfo].default_runfiles.root_symlinks.to_list():
- resources.append(make_resource_struct(src = mapping.target_file, dest = mapping.path))
-
- for f in dep.files.to_list():
- resources.append(make_resource_struct(src = f, dest = f.short_path))
-
- for src, dest in ctx.attr.content.items():
- files_list = src[DefaultInfo].files.to_list()
- if not dest.endswith("/") and len(files_list) > 1:
- fail("To map multiple files in %s, the content mapping %s should end with a slash to indicate a directory." % (ctx.label.name, dest))
-
- # pkgctl does not play well with paths starting with "/"
- dest = dest.lstrip("/")
-
- for f in files_list:
- d = dest
- if dest.endswith("/"):
- d = d + f.basename
-
- resources.append(make_resource_struct(src = f, dest = d))
-
- return [
- FuchsiaComponentInfo(
- name = component_name,
- manifest = manifest,
- resources = resources,
- is_driver = ctx.attr.is_driver,
- is_test = ctx.attr._variant == "test",
- ),
- collect_debug_symbols(ctx.attr.deps, ctx.attr.content.keys()),
- ]
-
-_fuchsia_component, _fuchsia_component_test = rule_variants(
- variants = (None, "test"),
- doc = """Creates a Fuchsia component which can be added to a package
-
-This rule will take a component manifest and compile it into a form that
-is suitable to be included in a package. The component can include any
-number of dependencies which will be included in the final package.
-""",
- implementation = _fuchsia_component_impl,
- attrs = {
- "deps": attr.label_list(
- doc = "A list of targets that this component depends on",
- ),
- "content": attr.label_keyed_string_dict(
- doc = """A map of dependencies and their destination in the Fuchsia component.
- If a destination ends with a slash, it is assumed to be a directory""",
- mandatory = False,
- ),
- "manifest": attr.label(
- doc = "The component manifest file",
- allow_single_file = [".cm", ".cmx"],
- mandatory = True,
- ),
- "component_name": attr.string(
- doc = "The name of the package, defaults to the target name",
- ),
- "is_driver": attr.bool(
- doc = "True if this is a driver component",
- default = False,
- ),
- },
-)
-
-def _fuchsia_component_for_unit_test_impl(ctx):
- underlying_component = ctx.attr.unit_test[FuchsiaUnitTestComponentInfo].test_component
- return [
- underlying_component[FuchsiaComponentInfo],
- collect_debug_symbols(underlying_component),
- ]
-
-fuchsia_component_for_unit_test = rule_variant(
- variant = "test",
- doc = """Transforms a FuchsiaUnitTestComponentInfo into a test component.""",
- implementation = _fuchsia_component_for_unit_test_impl,
- attrs = {
- "unit_test": attr.label(
- doc = "The unit test to convert into a test component",
- providers = [FuchsiaUnitTestComponentInfo],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_component_manifest.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_component_manifest.bzl
deleted file mode 100644
index 3b2d28c..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_component_manifest.bzl
+++ /dev/null
@@ -1,166 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaComponentManifestShardCollectionInfo", "FuchsiaComponentManifestShardInfo")
-
-def _fuchsia_component_manifest_shard_collection_impl(ctx):
- return FuchsiaComponentManifestShardCollectionInfo(
- shards = [dep for dep in ctx.attr.deps],
- )
-
-fuchsia_component_manifest_shard_collection = rule(
- doc = """Encapsulates a collection of component manifests and their include paths.
-
- This rule is not intended to be used directly. Rather, it should be added to the
- fuchsia sdk toolchain to be added as implicity dependencies for all manifests.
-""",
- implementation = _fuchsia_component_manifest_shard_collection_impl,
- attrs = {
- "deps": attr.label_list(
- doc = "A list of component manifest shard targets to collect.",
- providers = [[FuchsiaComponentManifestShardInfo]],
- ),
- },
-)
-
-def _fuchsia_component_manifest_shard_impl(ctx):
- return [
- FuchsiaComponentManifestShardInfo(
- file = ctx.file.src,
- base_path = ctx.attr.include_path,
- ),
- ]
-
-fuchsia_component_manifest_shard = rule(
- doc = """Encapsulates a component manifest shard from a input file.
-""",
- implementation = _fuchsia_component_manifest_shard_impl,
- attrs = {
- "include_path": attr.string(
- doc = "Base path of the shard, used in includepath argument of cmc compile",
- mandatory = True,
- ),
- "src": attr.label(
- doc = "The component manifest shard",
- allow_single_file = [".cml"],
- ),
- },
-)
-
-def _fuchsia_component_manifest_impl(ctx):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- if not ctx.file.src and not ctx.attr.content:
- fail("Either 'src' or 'content' needs to be specified.")
-
- if ctx.file.src and ctx.attr.content:
- fail("Only one of 'src' and 'content' can be specified.")
-
- if ctx.file.src:
- manifest_in = ctx.file.src
- else:
- # create a manifest file from the given content
- if not ctx.attr.component_name:
- fail("Attribute 'component_name' has to be specified when using inline content.")
-
- manifest_in = ctx.actions.declare_file("%s.cml" % ctx.attr.component_name)
- ctx.actions.write(
- output = manifest_in,
- content = ctx.attr.content,
- is_executable = False,
- )
-
- # output should have the .cm extension
- manifest_out = ctx.actions.declare_file(manifest_in.basename[:-1])
-
- if ctx.configuration.coverage_enabled:
- coverage_shard = ctx.attr._sdk_coverage_shard[FuchsiaComponentManifestShardInfo]
- manifest_merged = ctx.actions.declare_file("%s_merged.cml" % manifest_in.basename[:-4])
- ctx.actions.run(
- executable = sdk.cmc,
- arguments = [
- "merge",
- "--output",
- manifest_merged.path,
- manifest_in.path,
- coverage_shard.file.path,
- ],
- inputs = [
- manifest_in,
- coverage_shard.file,
- ],
- outputs = [manifest_merged],
- )
- manifest_in = manifest_merged
-
- # use a dict to eliminate workspace root duplicates
- include_path_dict = {}
- includes = []
- for dep in ctx.attr.includes + sdk.cmc_includes[FuchsiaComponentManifestShardCollectionInfo].shards:
- if FuchsiaComponentManifestShardInfo in dep:
- shard = dep[FuchsiaComponentManifestShardInfo]
- includes.append(shard.file)
- include_path_dict[shard.file.owner.workspace_root + "/" + shard.base_path] = 1
-
- include_path = []
- for w in include_path_dict.keys():
- include_path.extend(["--includepath", w])
-
- ctx.actions.run(
- executable = sdk.cmc,
- arguments = [
- "compile",
- "--output",
- manifest_out.path,
- manifest_in.path,
- "--includeroot",
- manifest_in.path[:-len(manifest_in.basename)],
- ] + include_path,
- inputs = [manifest_in] + includes,
- outputs = [
- manifest_out,
- ],
- mnemonic = "CmcCompile",
- )
-
- return [
- DefaultInfo(files = depset([manifest_out])),
- ]
-
-fuchsia_component_manifest = rule(
- doc = """Compiles a component manifest from a input file.
-
-This rule will compile an input cml file and output a cm file. The file can,
-optionally, include additional cml files but they must be relative to the
-src file and included in the includes attribute.
-
-```
-{
- include: ["foo.cml", "some_dir/bar.cml"]
-}
-```
-""",
- implementation = _fuchsia_component_manifest_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "src": attr.label(
- doc = "The source manifest to compile",
- allow_single_file = [".cml"],
- ),
- "content": attr.string(
- doc = "Inline content for the manifest",
- ),
- "component_name": attr.string(
- doc = "Name of the component for inline manifests",
- ),
- "includes": attr.label_list(
- doc = "A list of dependencies which are included in the src cml",
- providers = [FuchsiaComponentManifestShardInfo],
- ),
- # This is to get the coverage.shard.cml in the SDK, so it can be merged
- # in when coverage is enabled.
- "_sdk_coverage_shard": attr.label(
- default = "@fuchsia_sdk//pkg/sys/testing:coverage",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_debug_symbols.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_debug_symbols.bzl
deleted file mode 100644
index 69270e2..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_debug_symbols.bzl
+++ /dev/null
@@ -1,118 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Utilities for extracting, creating, and manipulating debug symbols."""
-
-load(":providers.bzl", "FuchsiaDebugSymbolInfo")
-load(":utils.bzl", "flatten", "make_resource_struct")
-load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain")
-
-def strip_resources(ctx, resources):
- """Strips resources and returns FuchsiaDebugSymbolInfo."""
- build_id_dir = ctx.actions.declare_directory(ctx.label.name + "/.build-id")
- stripped_resources = []
- all_maybe_elf_files = []
- all_ids_txt = []
-
- # We need to make sure we have a unique set of inputs. If we have duplicate
- # resources then the ctx.actions.declare_file below will fail because it
- # will try to declare the same file twice. We only need to strip the resource
- # once so there is no need to attempt to stip duplicates.
- for r in depset(resources).to_list():
- ids_txt = ctx.actions.declare_file(r.src.path + "ids_txt")
- all_ids_txt.append(ids_txt)
- all_maybe_elf_files.append(r.src)
- stripped_resources.append(_maybe_process_elf(ctx, r, ids_txt))
-
- ctx.actions.run(
- executable = ctx.executable._generate_symbols_dir_tool,
- arguments = [build_id_dir.path] + [f.path for f in all_ids_txt],
- outputs = [build_id_dir],
- inputs = all_ids_txt + all_maybe_elf_files,
- mnemonic = "GenerateDebugSymbols",
- progress_message = "Generate dir with debug symbols for %s" % ctx.label,
- )
-
- return stripped_resources, FuchsiaDebugSymbolInfo(build_id_dirs = {
- "BUILD_WORKSPACE_DIRECTORY": depset([build_id_dir]),
- })
-
-def _maybe_process_elf(ctx, r, ids_txt):
- cc_toolchain = find_cc_toolchain(ctx)
- stripped = ctx.actions.declare_file(r.src.path + "_stripped")
-
- ctx.actions.run(
- outputs = [stripped, ids_txt],
- inputs = [r.src],
- tools = cc_toolchain.all_files,
- executable = ctx.executable._elf_strip_tool,
- progress_message = "Extracting debug symbols from %s" % r.src,
- mnemonic = "ExtractDebugFromELF",
- arguments = [
- cc_toolchain.objcopy_executable,
- r.src.path,
- stripped.path,
- ids_txt.path,
- ],
- )
-
- return make_resource_struct(
- src = stripped,
- dest = r.dest,
- )
-
-def _fuchsia_debug_symbols_impl(ctx):
- return [
- FuchsiaDebugSymbolInfo(build_id_dirs = {
- ctx.file.build_dir: depset(transitive = [
- target[DefaultInfo].files
- for target in ctx.attr.build_id_dirs
- ]),
- }),
- ]
-
-fuchsia_debug_symbols = rule(
- doc = """Rule-based constructor for FuchsiaDebugSymbolInfo.""",
- implementation = _fuchsia_debug_symbols_impl,
- attrs = {
- "build_dir": attr.label(
- doc = "A direct file child within a build directory used by zxdb to locate code.",
- mandatory = True,
- allow_single_file = True,
- ),
- "build_id_dirs": attr.label_list(
- doc = "The build_id directories with symbols to be registered.",
- mandatory = True,
- allow_files = True,
- ),
- },
-)
-
-def collect_debug_symbols(*targets_or_providers):
- build_id_dirs = [
- (target_or_provider if (
- hasattr(target_or_provider, "build_id_dirs")
- ) else target_or_provider[FuchsiaDebugSymbolInfo]).build_id_dirs
- for target_or_provider in flatten(targets_or_providers)
- if hasattr(target_or_provider, "build_id_dirs") or FuchsiaDebugSymbolInfo in target_or_provider
- ]
- return FuchsiaDebugSymbolInfo(build_id_dirs = {
- build_dir: depset(transitive = [
- build_dir_mapping[build_dir]
- for build_dir_mapping in build_id_dirs
- if build_dir in build_dir_mapping
- ])
- for build_dir in depset([
- file
- for file in flatten([build_id_dir.keys() for build_id_dir in build_id_dirs])
- if type(file) == "File"
- ]).to_list() + depset([
- string
- for string in flatten([build_id_dir.keys() for build_id_dir in build_id_dirs])
- if type(string) == "string"
- ]).to_list()
- })
-
-def get_build_id_dirs(debug_symbol_info):
- return flatten([depset.to_list() for depset in debug_symbol_info.build_id_dirs.values()])
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_driver_bind_rules.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_driver_bind_rules.bzl
deleted file mode 100644
index 0390415..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_driver_bind_rules.bzl
+++ /dev/null
@@ -1,144 +0,0 @@
-"""Implementation of cc_bind_rules rule"""
-
-load(":providers.bzl", "FuchsiaBindLibraryInfo")
-
-def _process_bindc_args(context):
- # Collect all the bind files and their filepaths that will be passed to bindc.
- inputs = []
- include_filepaths = []
-
- for dep in context.attr.deps:
- trans_srcs = dep[FuchsiaBindLibraryInfo].transitive_sources
- for src in trans_srcs.to_list():
- # Only add unique instances.
- if src.path in include_filepaths:
- continue
- inputs.append(src)
- if len(include_filepaths) == 0:
- include_filepaths.append("--include")
-
- include_filepaths.append(src.path)
-
- files_argument = []
- for file in context.files.rules:
- inputs.append(file)
- files_argument.append(file.path)
- return {
- "inputs": inputs,
- "files_argument": files_argument,
- "include_filepaths": include_filepaths,
- }
-
-def _bind_rules_header_impl(context):
- args = _process_bindc_args(context)
- sdk = context.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- context.actions.run(
- executable = sdk.bindc,
- arguments = [
- "compile",
- ] + args["include_filepaths"] +
- [
- "--output",
- context.outputs.output.path,
- ] + args["files_argument"],
- inputs = args["inputs"],
- outputs = [
- context.outputs.output,
- ],
- mnemonic = "Bindcheader",
- )
-
-def _fuchsia_driver_bind_bytecode_impl(context):
- args = _process_bindc_args(context)
- sdk = context.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- context.actions.run(
- executable = sdk.bindc,
- arguments = [
- "compile",
- "--output-bytecode",
- "--use-new-bytecode",
- ] + args["include_filepaths"] +
- [
- "--output",
- context.outputs.output.path,
- ] + args["files_argument"],
- inputs = args["inputs"],
- outputs = [
- context.outputs.output,
- ],
- mnemonic = "Bindcbc",
- )
-
-_bind_rules_header = rule(
- implementation = _bind_rules_header_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- output_to_genfiles = True,
- attrs = {
- "rules": attr.label(
- doc = "Path to the bind rules source file",
- mandatory = True,
- allow_single_file = True,
- ),
- "output": attr.output(
- mandatory = True,
- ),
- "deps": attr.label_list(
- doc = "The list of libraries this library depends on",
- mandatory = False,
- providers = [FuchsiaBindLibraryInfo],
- ),
- },
-)
-
-fuchsia_driver_bind_bytecode = rule(
- implementation = _fuchsia_driver_bind_bytecode_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "rules": attr.label(
- doc = "Path to the bind rules source file",
- mandatory = True,
- allow_single_file = True,
- ),
- "output": attr.output(
- mandatory = True,
- ),
- "deps": attr.label_list(
- doc = "The list of libraries this library depends on",
- mandatory = False,
- providers = [FuchsiaBindLibraryInfo],
- ),
- },
-)
-
-def fuchsia_driver_bind_header(name, rules, output = None, deps = None, tags = None, **kwargs):
- """Generates cc_library() for the given bind rules.
-
- Args:
- name: Target name. Required.
- rules: Bind rules file. Required.
- output: Name of generated header file. Defaults to name + ".h".
- deps: Additional dependencies.
- tags: Optional tags.
- **kwargs: Remaining args.
- """
-
- if not output:
- output = "%s.h" % name
- gen_name = "%s_gen" % name
-
- _bind_rules_header(
- name = gen_name,
- output = output,
- rules = rules,
- deps = deps,
- visibility = ["//visibility:private"],
- )
-
- native.cc_library(
- tags = tags,
- name = name,
- hdrs = [
- ":%s" % gen_name,
- ],
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_driver_tool.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_driver_tool.bzl
deleted file mode 100644
index c604abe..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_driver_tool.bzl
+++ /dev/null
@@ -1,85 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaDriverToolInfo", "FuchsiaPackageResourcesInfo")
-
-def _find_binary_resource(resources, tool_entry_point):
- bin = None
- if tool_entry_point:
- for resource in resources:
- if resource.dest == tool_entry_point:
- bin = resource
- break
- else:
- for resource in resources:
- if resource.dest.startswith("bin"):
- if bin != None:
- fail("Multiple binaries found. Please specify a single binary.")
- bin = resource
-
- if bin == None:
- fail("Unable to find a suitable binary in the given resources.")
-
- return bin
-
-def _fuchsia_driver_tool_impl(ctx):
- if FuchsiaPackageResourcesInfo in ctx.attr.binary:
- resources = ctx.attr.binary[FuchsiaPackageResourcesInfo].resources
- else:
- resources = []
-
- bin = _find_binary_resource(resources, ctx.attr.tool_entry_point)
-
- return [
- FuchsiaDriverToolInfo(
- binary = bin,
- resources = resources,
- ),
- ]
-
-fuchsia_driver_tool = rule(
- doc = """Creates a tool which can be used with ffx driver run-tool.
-
- This rule will create a tool which can be used in the development of a driver.
- The rule takes a binary which is what will be executed when it runs. When the
- tool is added to a package it can be executed via `bazel run my_pkg.my_tool`.
- This will create a package server, publish the package and call `ffx driver run-tool`
-
- ```
- fuchsia_cc_binary(
- name = "bin",
- srcs = [ "main.cc" ],
- )
-
- fuchsia_driver_tool(
- name = "my_tool",
- binary = ":bin",
- )
-
- fuchsia_package(
- name = "pkg",
- tools = [ ":my_tool" ]
- )
-
- $ bazel run //pkg.my_tool -- --arg1 foo --arg2 bar
- """,
- implementation = _fuchsia_driver_tool_impl,
- attrs = {
- "binary": attr.label(
- doc = "The binary and its resources.",
- mandatory = True,
- providers = [[FuchsiaPackageResourcesInfo]],
- ),
- "tool_entry_point": attr.string(
- doc = """The path to the binaries entry point in the package.
-
- The path to the entry point will be inferred by the passed in binary
- if this value is not set. By default, the rule will look for a binary
- in bin/ and use that value. If the package containing the tool does
- not put the executable in bin/ or if bin/ contains multiple entries
- then this attribute must be set.
- """,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_emulator.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_emulator.bzl
deleted file mode 100644
index 56f9e2e..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_emulator.bzl
+++ /dev/null
@@ -1,107 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- "//fuchsia/private/workflows:fuchsia_emulator_tasks.bzl",
- "fuchsia_task_emulator_wait",
- "fuchsia_task_make_default_emulator",
- "fuchsia_task_reboot_emulator",
- "fuchsia_task_start_emulator",
- "fuchsia_task_stop_emulator",
-)
-load("//fuchsia/private:providers.bzl", "FuchsiaEmulatorInfo")
-load("//fuchsia/private/workflows:fuchsia_task_verbs.bzl", "make_help_executable", "verbs")
-
-def fuchsia_emulator(
- name,
- product_bundle,
- launch_options = None,
- emulator_name = None,
- **kwargs):
- """Describes a fuchsia_emulator instance and the tasks which control it.
-
- The following tasks will be created:
- - name.start: Starts the emulator
- - name.stop: Stops the emulator
- - name.reboot: Reboots the emulator
- - name.wait: waits for the emulator to come online.
- - name.make_default: Makes the emulator the default.
-
- Args:
- name: The target name.
- emulator_name: The name of the emulator. Defaults to name.
- product_bundle: The product bundle associated with this emulator.
- launch_options: Additional options to launch the emulator with.
- **kwargs: Extra attributes to pass along to the build rule.
- """
- _fuchsia_emulator(
- name = name,
- emulator_name = emulator_name,
- launch_options = launch_options,
- **kwargs
- )
-
- fuchsia_task_start_emulator(
- name = verbs.start(name),
- emulator = name,
- product_bundle = product_bundle,
- **kwargs
- )
-
- fuchsia_task_stop_emulator(
- name = verbs.stop(name),
- emulator = name,
- **kwargs
- )
-
- fuchsia_task_reboot_emulator(
- name = verbs.reboot(name),
- emulator = name,
- **kwargs
- )
-
- fuchsia_task_emulator_wait(
- name = verbs.wait(name),
- emulator = name,
- **kwargs
- )
-
- fuchsia_task_make_default_emulator(
- name = verbs.make_default(name),
- emulator = name,
- **kwargs
- )
-
-def _fuchsia_emulator_impl(ctx):
- return [
- DefaultInfo(executable = make_help_executable(
- ctx,
- {
- verbs.start: "Starts the emulator",
- verbs.stop: "Stops the emulator",
- verbs.reboot: "Reboots the emulator",
- verbs.wait: "Waits for the emulator to come online",
- verbs.make_default: "Make the emulator the default",
- },
- )),
- FuchsiaEmulatorInfo(
- name = ctx.attr.emulator_name or ctx.label.name,
- launch_options = ctx.attr.launch_options,
- ),
- ]
-
-_fuchsia_emulator = rule(
- implementation = _fuchsia_emulator_impl,
- doc = "A rule describing a fuchsia emulator.",
- attrs = {
- "emulator_name": attr.string(
- doc = "What to name the emulator, defaults to the target name",
- ),
- "launch_options": attr.string_list(
- doc = "A list of additional options to start the emulator with",
- default = [],
- ),
- },
- executable = True,
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_fidl_bind_library.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_fidl_bind_library.bzl
deleted file mode 100644
index 0a05f3a..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_fidl_bind_library.bzl
+++ /dev/null
@@ -1,79 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""A fuchsia_bind_library backed by a FIDL library."""
-
-load(":fuchsia_bind_library.bzl", "fuchsia_bind_library")
-load(":providers.bzl", "FuchsiaFidlLibraryInfo")
-
-def _bindlibgen_impl(context):
- sdk = context.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- bindc = sdk.bindc
-
- ir = context.attr.library[FuchsiaFidlLibraryInfo].ir
- fidl_lib_name = context.attr.library[FuchsiaFidlLibraryInfo].name
-
- base_path = context.attr.name
-
- # This declaration is needed in order to get access to the full path.
- root = context.actions.declare_directory(base_path)
-
- # The generated bind library file
- bindlib_relative = "/fidl_bindlibs/" + fidl_lib_name + ".bind"
- bindlib = [context.actions.declare_file(base_path + bindlib_relative)]
-
- outputs = [root] + bindlib
- context.actions.run(
- executable = bindc,
- arguments = [
- "generate-bind",
- "--output",
- root.path + bindlib_relative,
- ir.path,
- ],
- inputs = [
- ir,
- ],
- outputs = outputs,
- mnemonic = "FidlGenBindlib",
- )
-
- return [
- DefaultInfo(files = depset(bindlib)),
- ]
-
-# Runs bindc to produce the bind library file.
-_bindlibgen = rule(
- implementation = _bindlibgen_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "library": attr.label(
- doc = "The FIDL library to generate bind library for",
- mandatory = True,
- allow_files = False,
- providers = [FuchsiaFidlLibraryInfo],
- ),
- },
-)
-
-def fuchsia_fidl_bind_library(name, library, **kwargs):
- """Generates fuchsia_bind_library() for the given fidl_library.
-
- Args:
- name: Target name. Required.
- library: fidl_library() target to generate the language bindings for. Required.
- **kwargs: Remaining args.
- """
- gen_name = "%s_gen" % name
-
- _bindlibgen(
- name = gen_name,
- library = library,
- )
-
- fuchsia_bind_library(
- name = name,
- srcs = [":%s" % gen_name],
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_fidl_cc_library.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_fidl_cc_library.bzl
deleted file mode 100644
index eff5ec6..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_fidl_cc_library.bzl
+++ /dev/null
@@ -1,262 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""A cc_library backed by a FIDL library."""
-
-load(":providers.bzl", "FuchsiaFidlLibraryInfo")
-
-_CodegenInfo = provider("Carries generated information across FIDL bindings code generation ", fields = ["files"])
-
-def _typed_deps(deps, binding_type):
- result = []
- for dep in deps:
- if ":" in dep: # appends the binding_type suffix
- dep_with_binding = get_cc_lib_name(dep, binding_type)
- else:
- # assumption: this is a path with an implicit target name
- # TODO: THIS WILL FAIL eventually with local targets without ":" for example.
- # A better implementation is needed! We can't use Label() here because this is evaluated
- # in the generator context, not the SDK context.
- # One possible better implementation is to make fuchsia_fidl carry all the transitive dependencies per
- # cc binding type, and provide them as a Provider, and then just collect them in _codegen and make them
- # _codegen's own dependencies, which would probably cause native.cc_library to do the right thing.
- dep_label = dep.rpartition("/")[2]
- dep_label = get_cc_lib_name(dep_label, binding_type)
- dep_with_binding = "%s:%s" % (dep, dep_label)
-
- result.append(dep_with_binding)
- return result
-
-def get_cc_lib_name(fidl_target_name, binding_type):
- return "{fidl}_{binding_type}".format(fidl = fidl_target_name, binding_type = binding_type)
-
-def fuchsia_fidl_cc_library(name, library, binding_type = "cpp_wire", sdk_for_default_deps = None, deps = [], tags = [], **kwargs):
- """Generates cc_library() for the given fidl_library.
-
- Args:
- name: Target name. Required.
- library: fidl_library() target to generate the language bindings for. Required.
- binding_type: the FIDL binding type, for example "cpp_wire", "cpp_driver" or "cpp_natural_types". Defaults to "cpp_wire"
- sdk_for_default_deps: Name of the Bazel workspace where default FIDL library dependencies are defined. If empty or not defined, defaults to the current repository.
- deps: Additional dependencies.
- tags: Optional tags.
- **kwargs: Remaining args.
- """
- gen_name = "%s_codegen" % name
- impl_name = "%s_impl" % name
-
- _codegen(
- name = gen_name,
- library = library,
- binding_type = binding_type,
- sdk_for_default_deps = sdk_for_default_deps,
- )
-
- _impl_wrapper(
- name = impl_name,
- codegen = ":%s" % gen_name,
- )
-
- native.cc_library(
- name = name,
- hdrs = [
- ":%s" % gen_name,
- ],
- srcs = [
- ":%s" % impl_name,
- # For the coding tables.
- library,
- ],
- # This is necessary in order to locate generated headers.
- strip_include_prefix = gen_name + "." + binding_type,
- deps = _typed_deps(deps, binding_type) + _get_binding_info(sdk_for_default_deps, binding_type)["deps"],
- tags = tags,
- **kwargs
- )
-
-def _codegen_impl(context):
- sdk = context.toolchains["@rules_fuchsia//fuchsia:toolchain"]
-
- ir = context.attr.library[FuchsiaFidlLibraryInfo].ir
- name = context.attr.library[FuchsiaFidlLibraryInfo].name
-
- base_path = context.attr.name + "." + context.attr.binding_type
-
- # This declaration is needed in order to get access to the full path.
- root = context.actions.declare_directory(base_path)
-
- b = _get_binding_info(context.attr.sdk_for_default_deps, context.attr.binding_type)
- header_files = []
- header_files.extend(b["headers"])
- source_files = []
- source_files.extend(b["sources"])
- for layer_dep in b["layer_deps"]:
- layer_dep_b = _get_binding_info(context.attr.sdk_for_default_deps, layer_dep)
- header_files.extend(layer_dep_b["headers"])
- source_files.extend(layer_dep_b["sources"])
-
- # TODO(fxbug.dev/108680): Better workaround for skipping codegen for zx.
- if name == "zx":
- source_files = ["markers.h"]
-
- dir = base_path + "/fidl/" + name + "/cpp"
-
- headers = []
- sources = []
- for header in header_files:
- headers.append(context.actions.declare_file(dir + "/" + header))
- for source in source_files:
- sources.append(context.actions.declare_file(dir + "/" + source))
-
- outputs = [root] + headers + sources
- context.actions.run(
- executable = sdk.fidlgen_cpp,
- arguments = [
- "--json",
- ir.path,
- "--root",
- root.path,
- ],
- inputs = [
- ir,
- ],
- outputs = outputs,
- mnemonic = "FidlGenCc",
- )
-
- return [
- _CodegenInfo(files = depset(sources)),
- DefaultInfo(files = depset(headers)),
- ]
-
-# Runs fidlgen to produce both the header file and the implementation file.
-# Only exposes the header as a source, as the two files need to be consumed by
-# the cc_library as two separate rules.
-_codegen = rule(
- implementation = _codegen_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- # Files must be generated in genfiles in order for the header to be included
- # anywhere.
- output_to_genfiles = True,
- attrs = {
- "library": attr.label(
- doc = "The FIDL library to generate code for",
- mandatory = True,
- allow_files = False,
- providers = [FuchsiaFidlLibraryInfo],
- ),
- "binding_type": attr.string(
- doc = "Type of bindings to expose",
- mandatory = True,
- ),
- "sdk_for_default_deps": attr.string(
- doc = "Name of the Bazel workspace where default FIDL library dependencies are defined. If empty or not defined, defaults to the current repository.",
- mandatory = False,
- ),
- },
-)
-
-def _impl_wrapper_impl(context):
- files = context.attr.codegen[_CodegenInfo].files
- return [DefaultInfo(files = files)]
-
-# Simply declares the implementation file generated by the codegen target as an
-# output.
-# This allows the implementation file to be exposed as a source in its own rule.
-_impl_wrapper = rule(
- implementation = _impl_wrapper_impl,
- output_to_genfiles = True,
- attrs = {
- "codegen": attr.label(
- doc = "The codegen rules generating the implementation file",
- mandatory = True,
- allow_files = False,
- providers = [_CodegenInfo],
- ),
- },
-)
-
-def _get_binding_info(sdk_for_default_deps, binding_type):
- # Note: deps needs to be flattened, since Starlark does not support
- # recursivity or unbounded loops.
- if not sdk_for_default_deps:
- sdk_for_default_deps = ""
-
- wire_dep = sdk_for_default_deps + "//pkg/fidl_cpp_wire"
- natural_dep = sdk_for_default_deps + "//pkg/fidl_cpp_v2"
- driver_dep = sdk_for_default_deps + "//pkg/fidl_driver"
- driver_natural_dep = sdk_for_default_deps + "//pkg/fidl_driver_natural"
-
- bindings = {
- "cpp_common": {
- "headers": ["common_types.h", "markers.h"],
- "sources": ["common_types.cc"],
- "layer_deps": [],
- "deps": [wire_dep],
- },
- "cpp_wire_types": {
- "headers": ["wire_types.h"],
- "sources": ["wire_types.cc"],
- "layer_deps": ["cpp_common"],
- "deps": [],
- },
- "cpp_wire": {
- "headers": ["wire.h", "wire_messaging.h"],
- "sources": ["wire_messaging.cc"],
- "layer_deps": ["cpp_wire_types", "cpp_common"],
- "deps": [wire_dep],
- },
- "cpp_wire_testing": {
- "headers": ["wire_test_base.h"],
- "sources": [""],
- "layer_deps": ["cpp_wire", "cpp_wire_types", "cpp_common"],
- "deps": [],
- },
- "cpp_natural_types": {
- "headers": ["natural_types.h"],
- "sources": ["natural_types.cc"],
- "layer_deps": ["cpp_common"],
- "deps": [],
- },
- "cpp_natural_ostream": {
- "headers": ["natural_ostream.h"],
- "sources": ["natural_ostream.cc"],
- "layer_deps": ["cpp_natural_types", "cpp_common"],
- "deps": [],
- },
- "cpp_type_conversions": {
- "headers": ["type_conversions.h"],
- "sources": ["type_conversions.cc"],
- "layer_deps": ["cpp_natural_types", "cpp_wire", "cpp_common", "cpp_wire_types"],
- "deps": [],
- },
- "cpp": {
- "headers": ["fidl.h", "natural_messaging.h"],
- "sources": ["natural_messaging.cc"],
- "layer_deps": ["cpp_natural_types", "cpp_type_conversions", "cpp_wire", "cpp_common", "cpp_wire_types"],
- "deps": [wire_dep, natural_dep],
- },
- "cpp_driver_wire": {
- "headers": ["driver/wire.h", "driver/wire_messaging.h"],
- "sources": ["driver/wire_messaging.cc"],
- "layer_deps": ["cpp_wire_types", "cpp_common"],
- "deps": [wire_dep, driver_dep],
- },
- "cpp_driver": {
- "headers": ["driver/wire.h", "driver/wire_messaging.h", "natural_messaging.h", "driver/natural_messaging.h"],
- "sources": ["driver/wire_messaging.cc", "natural_messaging.cc", "driver/natural_messaging.cc"],
- "layer_deps": ["cpp_wire_types", "cpp_common", "cpp_natural_types", "cpp_type_conversions", "cpp_wire"],
- "deps": [wire_dep, natural_dep, driver_dep, driver_natural_dep],
- },
- "cpp_hlcpp_conversion": {
- "headers": ["hlcpp_conversion.h"],
- "sources": [""],
- "layer_deps": ["cpp_natural_types", "cpp_common"],
- "deps": [],
- },
- }
-
- if binding_type not in bindings:
- fail("Unsupported binding type: %s" % binding_type)
- return bindings[binding_type]
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_fidl_library.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_fidl_library.bzl
deleted file mode 100644
index 180524f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_fidl_library.bzl
+++ /dev/null
@@ -1,144 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for declaring a FIDL library"""
-
-load(":providers.bzl", "FuchsiaFidlLibraryInfo")
-load(":fuchsia_fidl_cc_library.bzl", "fuchsia_fidl_cc_library", "get_cc_lib_name")
-
-def _gather_dependencies(deps):
- info = []
- libs_added = []
- for dep in deps:
- for lib in dep[FuchsiaFidlLibraryInfo].info:
- name = lib.name
- if name in libs_added:
- continue
- libs_added.append(name)
- info.append(lib)
- return info
-
-def _fidl_impl(context):
- sdk = context.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- ir = context.outputs.ir
- tables = context.outputs.coding_tables
- library_name = context.attr.library
-
- info = _gather_dependencies(context.attr.deps)
- info.append(struct(
- name = library_name,
- files = context.files.srcs,
- ))
-
- files_argument = []
- inputs = []
- for lib in info:
- files_argument += ["--files"] + [f.path for f in lib.files]
- inputs.extend(lib.files)
-
- # The default Fuchsia target API level of this package
- api_level = context.attr.target_api_level or str(sdk.default_fidl_target_api)
-
- context.actions.run(
- executable = sdk.fidlc,
- arguments = [
- "--json",
- ir.path,
- "--name",
- library_name,
- "--available",
- "fuchsia:%s" % api_level,
- "--tables",
- tables.path,
- ] + files_argument,
- inputs = inputs,
- outputs = [
- ir,
- tables,
- ],
- mnemonic = "Fidlc",
- )
-
- return [
- # Exposing the coding tables here so that the target can be consumed as a
- # C++ source.
- DefaultInfo(files = depset([tables])),
- # Passing library info for dependent libraries.
- FuchsiaFidlLibraryInfo(info = info, name = library_name, ir = ir),
- ]
-
-_fidl_library = rule(
- implementation = _fidl_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "library": attr.string(
- doc = "The name of the FIDL library",
- mandatory = True,
- ),
- "target_api_level": attr.string(
- doc = "The version of the Fuchsia platform that this FIDL library will be built for",
- mandatory = False,
- ),
- "srcs": attr.label_list(
- doc = "The list of .fidl source files",
- mandatory = True,
- allow_files = True,
- allow_empty = False,
- ),
- "deps": attr.label_list(
- doc = "The list of libraries this library depends on",
- mandatory = False,
- providers = [FuchsiaFidlLibraryInfo],
- ),
- "cc_bindings": attr.string_list(
- doc = "list of FIDL CC binding types that this library will generate",
- mandatory = False,
- ),
- },
- outputs = {
- # The intermediate representation of the library, to be consumed by bindings
- # generators.
- "ir": "%{name}.fidl.json",
- # The C coding tables.
- "coding_tables": "%{name}_tables.c",
- },
-)
-
-def fuchsia_fidl_library(name, srcs, library = None, target_api_level = None, sdk_for_default_deps = None, cc_bindings = [], deps = [], **kwargs):
- """
- A FIDL library.
-
- Args:
- name: Name of the target
- library: Name of the FIDL library, defaults to the library name
- target_api_level: The version of the Fuchsia platform that this FIDL library will be built for.
- srcs: List of source files.
- cc_bindings: list of FIDL CC binding types to generate. Each binding specified will be represented by
- a new target named {name}_{cc_binding} of type fuchsia_fidl_cc_library.
- deps: List of labels for FIDL libraries this library depends on.
- sdk_for_default_deps: Name of the Bazel workspace where default FIDL library dependencies are defined. If empty or not defined, defaults to the current repository.
- **kwargs: Remaining args to be passed to the C++ binding rules
- """
-
- if not library:
- library = name
-
- _fidl_library(
- library = library,
- name = name,
- target_api_level = target_api_level,
- srcs = srcs,
- deps = deps,
- cc_bindings = cc_bindings,
- )
-
- for cc_binding in cc_bindings:
- fuchsia_fidl_cc_library(
- name = get_cc_lib_name(name, cc_binding),
- library = library,
- binding_type = cc_binding,
- deps = deps,
- sdk_for_default_deps = sdk_for_default_deps,
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_local_package_repository.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_local_package_repository.bzl
deleted file mode 100644
index 3700c1c..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_local_package_repository.bzl
+++ /dev/null
@@ -1,125 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Build rule for Fuchsia repository
-
-load(
- ":providers.bzl",
- "FuchsiaLocalPackageRepositoryInfo",
- "FuchsiaPackageGroupInfo",
- "FuchsiaPackageInfo",
- "FuchsiaPackageRepoInfo",
-)
-load(
- "//fuchsia/private/workflows:fuchsia_package_repository_tasks.bzl",
- "fuchsia_package_repository_make_default",
- "fuchsia_task_repository_add_from_pm",
- "fuchsia_task_repository_create",
- "fuchsia_task_repository_delete",
-)
-load(
- "//fuchsia/private/workflows:fuchsia_workflow.bzl",
- "fuchsia_workflow",
-)
-load(
- "//fuchsia/private/workflows:fuchsia_task_verbs.bzl",
- "make_help_executable",
- "verbs",
-)
-
-def fuchsia_local_package_repository(
- name,
- repo_name,
- repo_path,
- **kwargs):
- """
- Describes a local fuchsia repository and the tasks which control it.
-
- The following tasks will be created:
- - name.delete: Deletes the repo
- - name.create: Creates the repo
- - name.make_default: Makes the repo the default.
-
- Args:
- name: The target name.
- repo_name: The name of the repository
- repo_path: The path of the repository.
- **kwargs: Extra attributes to pass along to the build rule.
- """
-
- _fuchsia_local_package_repository(
- name = name,
- repo_name = repo_name,
- repo_path = repo_path,
- **kwargs
- )
-
- fuchsia_task_repository_delete(
- name = verbs.delete(name),
- repository_name = repo_name,
- path = repo_path,
- **kwargs
- )
-
- fuchsia_task_repository_create(
- name = name + "_create_as_pm",
- repository = name,
- **kwargs
- )
-
- fuchsia_task_repository_add_from_pm(
- name = name + "_create_add_from_pm",
- repository = name,
- **kwargs
- )
-
- fuchsia_package_repository_make_default(
- name = verbs.make_default(name),
- repository = name,
- **kwargs
- )
-
- fuchsia_workflow(
- name = verbs.create(name),
- sequence = [
- name + "_create_as_pm",
- name + "_create_add_from_pm",
- ],
- **kwargs
- )
-
-def _fuchsia_local_package_repository_impl(ctx):
- return [
- DefaultInfo(executable = make_help_executable(
- ctx,
- {
- verbs.delete: "Deletes the repo",
- verbs.create: "Creates the repo",
- verbs.make_default: "Make the repo the default",
- },
- )),
- FuchsiaLocalPackageRepositoryInfo(
- repo_name = ctx.attr.repo_name,
- repo_path = ctx.attr.repo_path,
- ),
- ]
-
-_fuchsia_local_package_repository = rule(
- implementation = _fuchsia_local_package_repository_impl,
- doc = "A rule which describes a fuchsia package repository on a local machine",
- attrs = {
- "repo_name": attr.string(
- doc = "The name of the repository",
- mandatory = True,
- ),
- "repo_path": attr.string(
- doc = """
- The path to the repository on disk. If path is relative it will be
- created relative to the workspace root.
- """,
- mandatory = True,
- ),
- },
- executable = True,
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_package.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_package.bzl
deleted file mode 100644
index e51cb92..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_package.bzl
+++ /dev/null
@@ -1,425 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(
- ":providers.bzl",
- "FuchsiaComponentInfo",
- "FuchsiaDriverToolInfo",
- "FuchsiaPackageInfo",
- "FuchsiaPackageResourcesInfo",
-)
-load(":fuchsia_component.bzl", "fuchsia_component_for_unit_test")
-load(":fuchsia_debug_symbols.bzl", "collect_debug_symbols", "get_build_id_dirs", "strip_resources")
-load(":fuchsia_transition.bzl", "fuchsia_transition")
-load(":package_publishing.bzl", "package_repo_path_from_label", "publish_package")
-load(":utils.bzl", "label_name", "make_resource_struct", "rule_variants", "stub_executable")
-load("//fuchsia/private/workflows:fuchsia_package_tasks.bzl", "fuchsia_package_tasks")
-
-def fuchsia_package(
- *,
- name,
- package_name = None,
- archive_name = None,
- components = [],
- resources = [],
- tools = [],
- **kwargs):
- """Builds a fuchsia package.
-
- This rule produces a fuchsia package which can be published to a package
- server and loaded on a device.
-
- The rule will return both package manifest json file which can be used later
- in the build system and an archive (.far) of the package which can be shared.
-
- This macro will expand out into several fuchsia tasks that can be run by a
- bazel invocation. Given a package definition, the following targets will be
- created.
-
- ```
- fuchsia_package(
- name = "pkg",
- components = [":my_component"],
- tools = [":my_tool"]
- )
- ```
- - pkg.help: Calling run on this target will show the valid macro-expanded targets
- - pkg.publish: Calling run on this target will publish the package
- - pkg.my_component: Calling run on this target will call `ffx component run`
- with the component url if it is fuchsia_component instance and will
- call `ffx driver register` if it is a fuchsia_driver_component.
- - pkg.my_tool: Calling run on this target will call `ffx driver run-tool` if
- the tool is a fuchsia_driver_tool
-
- Args:
- name: The target name.
- components: A list of components to add to this package. The dependencies
- of these targets will have their debug symbols stripped and added to
- the build-id directory.
- resources: A list of additional resources to add to this package. These
- resources will not have debug symbols stripped.
- tools: Additional tools that should be added to this package.
- package_name: An optional name to use for this package, defaults to name.
- archive_name: An option name for the far file.
- **kwargs: extra attributes to pass along to the build rule.
- """
- _build_fuchsia_package(
- name = "%s_fuchsia_package" % name,
- components = components,
- resources = resources,
- tools = tools,
- package_name = package_name or name,
- archive_name = archive_name,
- **kwargs
- )
-
- fuchsia_package_tasks(
- name = name,
- package = "%s_fuchsia_package" % name,
- components = {component: component for component in components},
- tools = {tool: tool for tool in tools},
- **kwargs
- )
-
-def _fuchsia_test_package(
- *,
- name,
- package_name = None,
- archive_name = None,
- resources = [],
- _test_component_mapping,
- _components = [],
- **kwargs):
- """Defines test variants of fuchsia_package.
-
- See fuchsia_package for argument descriptions."""
-
- _build_fuchsia_package_test(
- name = "%s_fuchsia_package" % name,
- test_components = _test_component_mapping.values(),
- components = _components,
- resources = resources,
- package_name = package_name or name,
- archive_name = archive_name,
- **kwargs
- )
-
- fuchsia_package_tasks(
- name = name,
- package = "%s_fuchsia_package" % name,
- components = _test_component_mapping,
- is_test = True,
- **kwargs
- )
-
-def fuchsia_test_package(
- *,
- name,
- test_components = [],
- components = [],
- **kwargs):
- """A test variant of fuchsia_package.
-
- See _fuchsia_test_package for additional arguments."""
- _fuchsia_test_package(
- name = name,
- _test_component_mapping = {component: component for component in test_components},
- _components = components,
- **kwargs
- )
-
-def fuchsia_unittest_package(
- *,
- name,
- package_name = None,
- archive_name = None,
- resources = [],
- unit_tests,
- **kwargs):
- """A variant of fuchsia_test_package containing unit tests.
-
- See _fuchsia_test_package for additional arguments."""
-
- test_component_mapping = {}
- for unit_test in unit_tests:
- test_component_mapping[unit_test] = "%s_unit_test" % label_name(unit_test)
- fuchsia_component_for_unit_test(
- name = test_component_mapping[unit_test],
- unit_test = unit_test,
- **kwargs
- )
-
- _fuchsia_test_package(
- name = name,
- package_name = package_name,
- archive_name = archive_name,
- resources = resources,
- _test_component_mapping = test_component_mapping,
- **kwargs
- )
-
-def _build_fuchsia_package_impl(ctx):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- archive_name = ctx.attr.archive_name or ctx.attr.package_name
-
- if not archive_name.endswith(".far"):
- archive_name += ".far"
-
- # where we will collect all of the temporary files
- pkg_dir = ctx.label.name + "_pkg/"
-
- # Declare all of the output files
- manifest = ctx.actions.declare_file(pkg_dir + "manifest")
- meta_package = ctx.actions.declare_file(pkg_dir + "meta/package")
- meta_far = ctx.actions.declare_file(pkg_dir + "meta.far")
- output_package_manifest = ctx.actions.declare_file(ctx.label.name + "_package_manifest.json")
- far_file = ctx.actions.declare_file(archive_name)
-
- # The Fuchsia target API level of this package
- api_level = sdk.default_api_level
-
- api_level_input = ["-api-level", str(api_level)]
-
- # All of the resources that will go into the package
- package_resources = [
- # Initially include the meta package
- make_resource_struct(
- src = meta_package,
- dest = "meta/package",
- ),
- ]
-
- # Resources that we will pass through the debug symbol stripping process
- resources_to_strip = []
- components = []
- drivers = []
-
- # Verify correctness of test vs non-test components.
- for test_component in ctx.attr.test_components:
- if not test_component[FuchsiaComponentInfo].is_test:
- fail("Please use `components` for non-test components.")
- for component in ctx.attr.components:
- if component[FuchsiaComponentInfo].is_test:
- fail("Please use `test_components` for test components.")
-
- # Collect all the resources from the deps
- for dep in ctx.attr.test_components + ctx.attr.components + ctx.attr.resources + ctx.attr.tools:
- if FuchsiaComponentInfo in dep:
- component_info = dep[FuchsiaComponentInfo]
- component_manifest = component_info.manifest
- component_dest = "meta/%s" % (component_manifest.basename)
- components.append(component_dest)
-
- if component_info.is_driver:
- drivers.append(component_dest)
-
- package_resources.append(
- # add the component manifest
- make_resource_struct(
- src = component_manifest,
- dest = component_dest,
- ),
- )
- resources_to_strip.extend([r for r in component_info.resources])
- elif FuchsiaDriverToolInfo in dep:
- resources_to_strip.extend(dep[FuchsiaDriverToolInfo].resources)
- elif FuchsiaPackageResourcesInfo in dep:
- # Don't strip debug symbols from resources.
- package_resources.extend(dep[FuchsiaPackageResourcesInfo].resources)
- else:
- fail("Unknown dependency type being added to package: %s" % dep.label)
-
- # Grab all of our stripped resources
- stripped_resources, _debug_info = strip_resources(ctx, resources_to_strip)
- package_resources.extend(stripped_resources)
-
- # Write our package_manifest file
- ctx.actions.write(
- output = manifest,
- content = "\n".join(["%s=%s" % (r.dest, r.src.path) for r in package_resources]),
- )
-
- # Create the meta/package file
- output_dir = manifest.dirname
- ctx.actions.run(
- executable = sdk.pm,
- arguments = [
- "-o", # output directory
- output_dir,
- "-n", # name of the package
- ctx.attr.package_name,
- "init",
- ],
- outputs = [
- meta_package,
- ],
- mnemonic = "FuchsiaPmInit",
- )
-
- # The only input to the build step is the manifest but we need to
- # include all of the resources as inputs so that if they change the
- # package will get rebuilt.
- build_inputs = [r.src for r in package_resources] + [
- manifest,
- meta_package,
- ]
-
- repo_name_args = ["-r", ctx.attr.package_repository_name] if (ctx.attr.package_repository_name != None) else []
-
- # Build the package
- ctx.actions.run(
- executable = sdk.pm,
- arguments = [
- "-o",
- output_dir,
- "-m",
- manifest.path,
- "-n",
- ctx.attr.package_name,
- ] + repo_name_args + api_level_input + [
- "build",
- "--output-package-manifest",
- output_package_manifest.path,
- ],
- inputs = build_inputs,
- outputs = [
- output_package_manifest,
- meta_far,
- ],
- mnemonic = "FuchsiaPmBuild",
- progress_message = "Building package for %s" % ctx.label,
- )
-
- # Create the far file.
- ctx.actions.run(
- executable = sdk.pm,
- arguments = [
- "-o",
- output_dir,
- "-m",
- manifest.path,
- "-n",
- ctx.attr.package_name,
- "archive",
- "-output",
- # pm automatically adds .far so we have to remove it here to make
- # bazel happy since we need to declare the output with the extension
- far_file.path[:-4],
- ],
- inputs = [meta_far, output_package_manifest] + build_inputs,
- outputs = [
- far_file,
- ],
- mnemonic = "FuchsiaPmArchive",
- progress_message = "Archiving package for %{label}",
- )
-
- output_files = [
- far_file,
- output_package_manifest,
- manifest,
- meta_far,
- ]
-
- # Attempt to publish if told to do so
- repo_path = package_repo_path_from_label(ctx.attr._package_repo_path)
- if repo_path:
- # TODO: collect all dependent packages
- stamp_file = publish_package(ctx, sdk.pm, repo_path, [output_package_manifest])
- output_files.append(stamp_file)
-
- # Sanity check that we are not trying to put 2 different resources at the same mountpoint
- collected_blobs = {}
- for resource in package_resources:
- if resource.dest in collected_blobs and resource.src.path != collected_blobs[resource.dest]:
- fail("Trying to add multiple resources with the same filename and different content")
- else:
- collected_blobs[resource.dest] = resource.src.path
-
- return [
- DefaultInfo(files = depset(output_files), executable = stub_executable(ctx)),
- FuchsiaPackageInfo(
- far_file = far_file,
- package_manifest = output_package_manifest,
- files = [output_package_manifest, meta_far] + build_inputs,
- package_name = ctx.attr.package_name,
- components = components,
- drivers = drivers,
- meta_far = meta_far,
- package_resources = package_resources,
-
- # TODO: Remove this field, change usages to FuchsiaDebugSymbolInfo.
- build_id_dir = get_build_id_dirs(_debug_info)[0],
- ),
- collect_debug_symbols(
- _debug_info,
- ctx.attr.test_components,
- ctx.attr.components,
- ctx.attr.resources,
- ctx.attr.tools,
- ctx.attr._fuchsia_sdk_debug_symbols,
- ),
- ]
-
-_build_fuchsia_package, _build_fuchsia_package_test = rule_variants(
- variants = (None, "test"),
- doc = "Builds a fuchsia package.",
- implementation = _build_fuchsia_package_impl,
- cfg = fuchsia_transition,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain", "@bazel_tools//tools/cpp:toolchain_type"],
- attrs = {
- "package_name": attr.string(
- doc = "The name of the package",
- mandatory = True,
- ),
- "archive_name": attr.string(
- doc = "What to name the archive. The .far file will be appended if not in this name. Defaults to package_name",
- ),
- # TODO(https://fxbug.dev/114334): Improve doc for this field when we
- # have more clarity from the bug.
- "package_repository_name": attr.string(
- doc = "Repository name of this package, defaults to None",
- ),
- "components": attr.label_list(
- doc = "The list of components included in this package",
- providers = [FuchsiaComponentInfo],
- ),
- "test_components": attr.label_list(
- doc = "The list of test components included in this package",
- providers = [FuchsiaComponentInfo],
- ),
- "resources": attr.label_list(
- doc = "The list of resources included in this package",
- providers = [FuchsiaPackageResourcesInfo],
- ),
- "tools": attr.label_list(
- doc = "The list of tools included in this package",
- providers = [FuchsiaDriverToolInfo],
- ),
- "_fuchsia_sdk_debug_symbols": attr.label(
- doc = "Include debug symbols from @fuchsia_sdk.",
- default = "@fuchsia_sdk//:debug_symbols",
- ),
- "_package_repo_path": attr.label(
- doc = "The command line flag used to publish packages.",
- default = "//fuchsia:package_repo",
- ),
- "_elf_strip_tool": attr.label(
- default = "//fuchsia/tools:elf_strip",
- executable = True,
- cfg = "exec",
- ),
- "_generate_symbols_dir_tool": attr.label(
- default = "//fuchsia/tools:generate_symbols_dir",
- executable = True,
- cfg = "exec",
- ),
- "_cc_toolchain": attr.label(
- default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
- ),
- "_allowlist_function_transition": attr.label(
- default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_package_group.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_package_group.bzl
deleted file mode 100644
index 05efe00..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_package_group.bzl
+++ /dev/null
@@ -1,53 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Build rule for pre-built Fuchsia Packages
-
-load(
- ":providers.bzl",
- "FuchsiaPackageGroupInfo",
- "FuchsiaPackageInfo",
-)
-load("//fuchsia/private/workflows:fuchsia_task_publish.bzl", "fuchsia_task_publish")
-
-def _fuchsia_package_group_impl(ctx):
- packages = []
- for dep in ctx.attr.deps:
- if FuchsiaPackageInfo in dep:
- packages.append(dep[FuchsiaPackageInfo])
- elif FuchsiaPackageGroupInfo in dep:
- packages.extend(dep[FuchsiaPackageGroupInfo].packages)
- return [
- DefaultInfo(files = depset(ctx.files.deps)),
- FuchsiaPackageGroupInfo(packages = packages),
- ]
-
-_fuchsia_package_group = rule(
- doc = """
-A group of Fuchsia packages, composed of all the packages and groups specified in deps.
-""",
- implementation = _fuchsia_package_group_impl,
- attrs = {
- "deps": attr.label_list(
- doc = "Fuchsia packages and package groups to include in this group.",
- providers = [
- [FuchsiaPackageInfo],
- [FuchsiaPackageGroupInfo],
- ],
- ),
- },
-)
-
-def fuchsia_package_group(*, name, deps, **kwargs):
- _fuchsia_package_group(
- name = name,
- deps = deps,
- **kwargs
- )
-
- fuchsia_task_publish(
- name = "%s.publish" % name,
- packages = [name],
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_package_repository.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_package_repository.bzl
deleted file mode 100644
index c5970ce..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_package_repository.bzl
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Build rule for Fuchsia repository
-
-load(
- ":providers.bzl",
- "FuchsiaPackageGroupInfo",
- "FuchsiaPackageInfo",
- "FuchsiaPackageRepoInfo",
-)
-
-def _fuchsia_package_repository_impl(ctx):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- repo_name = ctx.attr.repo_name or ctx.label.name
- packages = []
- package_deps = []
- for dep in ctx.attr.deps:
- if FuchsiaPackageInfo in dep:
- packages.append(dep[FuchsiaPackageInfo].package_manifest.path)
- package_deps.extend(dep[FuchsiaPackageInfo].files)
- package_deps.append(dep[FuchsiaPackageInfo].package_manifest)
-
- list_of_packages = ctx.actions.declare_file("%s_packages.list" % repo_name)
-
- ctx.actions.write(
- output = list_of_packages,
- content = "\n".join(packages),
- )
-
- # Publish the packages
- repo_dir = ctx.actions.declare_directory("%s.repo" % repo_name)
- ctx.actions.run(
- executable = sdk.pm,
- arguments = [
- "publish",
- "-C",
- "-lp",
- "-f",
- list_of_packages.path,
- "-repo",
- repo_dir.path,
- ],
- inputs = depset(package_deps + [list_of_packages]),
- outputs = [
- repo_dir,
- ],
- mnemonic = "FuchsiaPmPublish",
- progress_message = "Publishing package repository %{label}",
- )
-
- return [
- DefaultInfo(files = depset([repo_dir])),
- FuchsiaPackageRepoInfo(
- packages = packages,
- repo_dir = repo_dir.path,
- blobs = package_deps,
- ),
- ]
-
-fuchsia_package_repository = rule(
- doc = """
-A Fuchsia TUF package repository as created by the 'pm' tool and used by 'ffx repository'.
-""",
- implementation = _fuchsia_package_repository_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- provides = [FuchsiaPackageRepoInfo],
- attrs = {
- "deps": attr.label_list(
- doc = "Fuchsia package and package groups to include in this repository.",
- providers = [
- [FuchsiaPackageInfo],
- [FuchsiaPackageGroupInfo],
- ],
- ),
- "repo_name": attr.string(
- doc = "The repository name, defaults to the rule name",
- mandatory = False,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_package_resource.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_package_resource.bzl
deleted file mode 100644
index 8f51f11..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_package_resource.bzl
+++ /dev/null
@@ -1,85 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":providers.bzl", "FuchsiaPackageResourcesInfo")
-load(":utils.bzl", "make_resource_struct")
-
-def _package_resources_providers(ctx, resources):
- return [
- FuchsiaPackageResourcesInfo(resources = resources),
- # Note: We create a package_resource for our cc_binary distributions
- # in the SDK and we need to export the default info as a root symlink
- # to access them. This needs to exist until fuchsia_cc.bzl does not
- # need to access the root_symlinks.
- DefaultInfo(
- runfiles = ctx.runfiles(
- root_symlinks = {r.dest: r.src for r in resources},
- ),
- ),
- ]
-
-def _fuchsia_package_resource_impl(ctx):
- if len(ctx.attr.dest) == 0:
- fail("dest must not be an empty string")
-
- return _package_resources_providers(ctx, [make_resource_struct(
- src = ctx.files.src[0],
- dest = ctx.attr.dest,
- )])
-
-fuchsia_package_resource = rule(
- doc = """Declares a resource to be included in a Fuchsia package.
-
-`src` can be a static file or something generated by another rule.
-`dest` must be a path relative to /.
-
-This rule can be added as a dependency of a fuchsia_package and it
-will be added to the final package contents.
-""",
- implementation = _fuchsia_package_resource_impl,
- attrs = {
- "src": attr.label(
- doc = "The resource to include in the package.",
- mandatory = True,
- allow_single_file = True,
- ),
- "dest": attr.string(
- doc = "The path where this will be installed in the package.",
- mandatory = True,
- ),
- },
-)
-
-def _fuchsia_package_resource_group_impl(ctx):
- resources = []
- dest = ctx.attr.dest.removesuffix("/")
-
- for src in ctx.files.srcs:
- name = src.short_path.removeprefix(ctx.label.package + "/").removeprefix(ctx.attr.strip_prefix).removeprefix("/")
- resources.append(
- make_resource_struct(src = src, dest = dest + "/" + name),
- )
-
- return _package_resources_providers(ctx, resources)
-
-fuchsia_package_resource_group = rule(
- doc = """Declares a group of resources to be included in a Fuchsia package.
-""",
- implementation = _fuchsia_package_resource_group_impl,
- attrs = {
- "srcs": attr.label_list(
- doc = "The resource to include in the package.",
- mandatory = True,
- allow_files = True,
- ),
- "dest": attr.string(
- doc = "The path where this will be installed in the package.",
- mandatory = True,
- ),
- "strip_prefix": attr.string(
- doc = "A path to remove from the srcs",
- default = "",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_remote_product_bundle.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_remote_product_bundle.bzl
deleted file mode 100644
index b8704dd..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_remote_product_bundle.bzl
+++ /dev/null
@@ -1,97 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load("//fuchsia/private/workflows:providers.bzl", "FuchsiaProductBundleInfo")
-load("//fuchsia/private/workflows:fuchsia_product_bundle_tasks.bzl", "fuchsia_task_fetch_product_bundle", "fuchsia_task_remove_product_bundle")
-load(
- "//fuchsia/private/workflows:fuchsia_package_repository_tasks.bzl",
- "fuchsia_task_repository_delete",
-)
-load("//fuchsia/private/workflows:fuchsia_task_verbs.bzl", "make_help_executable", "verbs")
-
-def fuchsia_remote_product_bundle(
- name,
- product_name,
- version = None,
- repository = None,
- **kwargs):
- """
- Describes a product bundle which is not built locally and the tasks which fetch it.
-
- The following tasks will be created:
- - name.fetch: Fetches the product bundle
- - name.remove: Removes the product bundle
- - name.delete_repo: Deletes the repository associated with this bundle
-
- Args:
- name: The target name.
- product_name: The name of the product to fetch.
- version: A specific version to fetch. Defaults to the sdk version.
- repository: The name of the repository to host the product bundle's packages.
- **kwargs: Extra attributes to pass along to the build rule.
- """
- _fuchsia_remote_product_bundle(
- name = name,
- product_name = product_name,
- version = version,
- repository = repository,
- )
-
- fuchsia_task_fetch_product_bundle(
- name = verbs.fetch(name),
- product_bundle = name,
- )
-
- fuchsia_task_remove_product_bundle(
- name = verbs.remove(name),
- product_bundle = name,
- )
-
- fuchsia_task_repository_delete(
- name = verbs.delete_repo(name),
- repository_name = repository or product_name,
- preserve_contents = True,
- )
-
-def _fuchsia_remote_product_bundle_impl(ctx):
- return [
- DefaultInfo(executable = make_help_executable(
- ctx,
- {
- verbs.fetch: "Fetches the product bundle",
- verbs.remove: "Removes the product bundle",
- verbs.delete_repo: "Deletes the repository associated with this bundle",
- },
- )),
- FuchsiaProductBundleInfo(
- is_remote = True,
- product_bundle = ctx.attr.product_name,
- product_name = ctx.attr.product_name,
- version = ctx.attr.version,
- repository = ctx.attr.repository,
- ),
- ]
-
-_fuchsia_remote_product_bundle = rule(
- implementation = _fuchsia_remote_product_bundle_impl,
- doc = "A rule describing a remote product bundle.",
- attrs = {
- "product_name": attr.string(
- doc = "The name of the product to download",
- mandatory = True,
- ),
- "version": attr.string(
- doc = """
- The version of the product bundle. If not supplied will default to
- the version specified by the SDK""",
- ),
- "repository": attr.string(
- doc = """
- The name of the repository to host the packages in the product bundle.
- If not provided the product_name will be used.
- """,
- ),
- },
- executable = True,
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_rust.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_rust.bzl
deleted file mode 100644
index be15ee7..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_rust.bzl
+++ /dev/null
@@ -1,80 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Wrappers for providing FuchsiaPackageResourcesInfo for rust binaries."""
-
-load(":utils.bzl", "get_runfiles", "is_lib", "make_resource_struct")
-load(":providers.bzl", "FuchsiaPackageResourcesInfo")
-
-def _fuchsia_wrap_rust_impl(ctx):
- # Expect exactly one binary to be generated by the wrapped binary rule.
- native_outputs = ctx.attr.native_target.files.to_list()
- if len(native_outputs) != 1:
- fail("Expected exactly 1 native output for %s, got %s" % (ctx.attr.native_target, native_outputs))
-
- resources = [
- # The binary generated by the native rust_* rule.
- make_resource_struct(src = native_outputs[0], dest = "bin/" + ctx.attr.bin_name),
- ]
- for data in ctx.attr.data:
- resources.extend(data[FuchsiaPackageResourcesInfo].resources)
- for file in get_runfiles(ctx.attr.native_target):
- if is_lib(file):
- resources.append(make_resource_struct(src = file, dest = "lib/" + file.basename))
- return FuchsiaPackageResourcesInfo(resources = resources)
-
-_fuchsia_wrap_rust_binary = rule(
- implementation = _fuchsia_wrap_rust_impl,
- doc = """Attaches fuchsia-specific metadata to rust_binary targets.
-
- This allows them to be directly included in fuchsia_component.
- """,
- attrs = {
- "bin_name": attr.string(
- doc = "The name of the executable to place under bin/.",
- mandatory = True,
- ),
- "native_target": attr.label(
- doc = "The underlying cc_* target.",
- mandatory = True,
- providers = [[DefaultInfo]],
- ),
- "data": attr.label_list(
- doc = "Packaged files needed by this target at runtime.",
- providers = [FuchsiaPackageResourcesInfo],
- ),
- },
-)
-
-def fuchsia_wrap_rust_binary(
- name = None,
- bin_name = None,
- native_binary = None,
- sdk_root_label = "@fuchsia_sdk",
- clang_root_label = "@fuchsia_clang",
- **kwargs):
- """Wrap a compiled rust binary.
-
- The resulting target can be used as a dep in fuchsia_component.
-
- Args:
- name: This target name.
- bin_name: The filename to place under bin/. Defaults to name.
- native_binary: The existing binary's target label.
- sdk_root_label: Optionally override the root label of the fuchsia sdk repo.
- clang_root_label: Optionally override the root label of the fuchsia clang repo.
- **kwargs: Misc arguments (like testonly and visibility) to forward to the underlying rule.
- """
-
- _fuchsia_wrap_rust_binary(
- name = name,
- bin_name = bin_name if bin_name != None else name,
- native_target = native_binary,
- data = [
- "%s//pkg/sysroot:dist" % sdk_root_label,
- "%s//:dist" % clang_root_label,
- "%s//:runtime" % clang_root_label,
- ],
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_select.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_select.bzl
deleted file mode 100644
index db6d2f2..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_select.bzl
+++ /dev/null
@@ -1,47 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Helpers for using select() within Fuchsia rules."""
-
-_ERROR = """
-****************************************************************************
-ERROR: You have to specify a config in order to build Fuchsia.
-For example:
- bazel build --config=fuchsia_x64 ...
- bazel build --config=fuchsia_arm64 ...
-****************************************************************************
-"""
-
-def fuchsia_select(configs):
- """select() variant that prints a meaningful error.
-
- Args:
- configs: A dict of config name-value pairs.
-
- Returns:
- Selected attribute value depending on the config.
- """
- return select(configs, no_match_error = _ERROR)
-
-# TODO(jayzhuang): Remove this function when downstream usages are removed.
-def if_fuchsia(value, if_not = [], _unused_rules_fuchsia_root = "@rules_fuchsia"):
- """Selects `value` if targeting Fuchsia. Otherwise selects `if_not`.
-
- Args:
- value: The value to select for if targeting Fuchsia.
- if_not: The value to select for if not targeting Fuchsia.
- rules_fuchsia_root: The root label for rules_fuchsia (this repo).
- Returns:
- Selected value depending on whether we're targeting Fuchsia.
- """
- return fuchsia_select({
- "@platforms//os:fuchsia": value,
- "//conditions:default": if_not,
- })
-
-def fuchsia_only_target():
- return if_fuchsia(
- [],
- ["@platforms//:incompatible"],
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/fuchsia_transition.bzl b/bazel_rules_fuchsia/fuchsia/private/fuchsia_transition.bzl
deleted file mode 100644
index 9342648..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/fuchsia_transition.bzl
+++ /dev/null
@@ -1,118 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Utilities for changing the build configuration to fuchsia."""
-
-load(":fuchsia_select.bzl", "if_fuchsia")
-load(":utils.bzl", "alias", "forward_providers", "rule_variants")
-
-NATIVE_CPU_ALIASES = {
- "darwin": "x86_64",
- "k8": "x86_64",
- "x86_64": "x86_64",
- "armeabi-v7a": "aarch64",
- "aarch64": "aarch64",
-}
-
-FUCHSIA_PLATFORMS_MAP = {
- "x86_64": "fuchsia_x64",
- "aarch64": "fuchsia_arm64",
-}
-
-def _fuchsia_transition_impl(settings, _):
- input_cpu = settings["//command_line_option:cpu"]
- output_cpu = NATIVE_CPU_ALIASES.get(input_cpu, None)
- if not output_cpu:
- fail("Unrecognized cpu %s." % input_cpu)
- fuchsia_platform = "@rules_fuchsia//fuchsia/constraints/platforms:" + FUCHSIA_PLATFORMS_MAP[output_cpu]
- copt = settings["//command_line_option:copt"] + (
- [] if "--debug" in settings["//command_line_option:copt"] else ["--debug"]
- )
- return {
- "//command_line_option:cpu": output_cpu,
- "//command_line_option:crosstool_top": "@fuchsia_clang//:toolchain",
- "//command_line_option:host_crosstool_top": "@bazel_tools//tools/cpp:toolchain",
- "//command_line_option:copt": copt,
- "//command_line_option:strip": "never",
- "//command_line_option:platforms": fuchsia_platform,
- }
-
-fuchsia_transition = transition(
- implementation = _fuchsia_transition_impl,
- inputs = [
- "//command_line_option:cpu",
- "//command_line_option:copt",
- ],
- outputs = [
- "//command_line_option:cpu",
- "//command_line_option:crosstool_top",
- "//command_line_option:host_crosstool_top",
- "//command_line_option:copt",
- "//command_line_option:strip",
- "//command_line_option:platforms",
- ],
-)
-
-def _forward_default_info(ctx):
- return forward_providers(ctx, ctx.attr.actual)
-
-(
- _with_fuchsia_transition,
- _with_fuchsia_transition_for_run,
- _with_fuchsia_transition_for_test,
-) = rule_variants(
- variants = (None, "executable", "test"),
- implementation = _forward_default_info,
- cfg = fuchsia_transition,
- doc = """Transitions build-only, build + run, or build + test targets.""",
- attrs = {
- "actual": attr.label(
- doc = "The target to transition.",
- mandatory = True,
- ),
- "_allowlist_function_transition": attr.label(
- default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
- ),
- },
-)
-
-def with_fuchsia_transition(
- *,
- name,
- actual,
- executable = True,
- testonly = False,
- **kwargs):
- """
- Applies fuchsia_transition on a target.
-
- Args:
- name: The target name.
- actual: The target to apply to.
- executable: Whether `target`[DefaultInfo] has an executable.
- testonly: Whether this is a test target.
- **kwargs: Additional kwargs to forward to the rule.
- """
- if not executable:
- transition = _with_fuchsia_transition
- elif not testonly:
- transition = _with_fuchsia_transition_for_run
- else:
- transition = _with_fuchsia_transition_for_test
- transition(
- name = name + "_with_transition",
- actual = actual,
- testonly = testonly,
- **kwargs
- )
- alias(
- name = name,
- actual = if_fuchsia(
- actual,
- if_not = name + "_with_transition",
- ),
- executable = executable,
- testonly = testonly,
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/legacy_fuchsia_fidl_cc_library.bzl b/bazel_rules_fuchsia/fuchsia/private/legacy_fuchsia_fidl_cc_library.bzl
deleted file mode 100644
index 73f959c..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/legacy_fuchsia_fidl_cc_library.bzl
+++ /dev/null
@@ -1,218 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""A cc_library backed by a FIDL library."""
-
-load(":providers.bzl", "FuchsiaFidlLibraryInfo")
-
-_CodegenInfo = provider("Carries generated information across FIDL bindings code generation ", fields = ["files"])
-
-# ALL CODE BELOW IS DEPRECATED - TODO: REMOVE IT when soft transition is over
-def _codegen_impl(context):
- sdk = context.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- fidlgen = sdk.fidlgen_cpp if context.attr.binding_level == "llcpp" else sdk.fidlgen_hlcpp
-
- ir = context.attr.library[FuchsiaFidlLibraryInfo].ir
- name = context.attr.library[FuchsiaFidlLibraryInfo].name
-
- base_path = context.attr.name + "." + context.attr.binding_level
-
- # This declaration is needed in order to get access to the full path.
- root = context.actions.declare_directory(base_path)
- headers = []
- sources = []
- if context.attr.binding_level == "llcpp":
- dir = base_path + "/fidl/" + name + "/cpp"
- header_files = []
- source_files = []
-
- # common:
- header_files.extend(["common_types.h", "markers.h"])
- source_files.extend(["common_types.cc"])
-
- # wire types:
- header_files.extend(["wire_types.h"])
- source_files.extend(["wire_types.cc"])
-
- # wire zircon:
- header_files.extend(["wire.h", "wire_messaging.h"])
- source_files.extend(["wire_messaging.cc"])
-
- # wire channel testing:
- header_files.extend(["wire_test_base.h"])
-
- # natural types:
- header_files.extend(["natural_types.h"])
- source_files.extend(["natural_types.cc"])
-
- # wire/natural type conversions:
- header_files.extend(["type_conversions.h"])
- source_files.extend(["type_conversions.cc"])
-
- # unified zircon channel messaging:
- header_files.extend(["fidl.h", "natural_messaging.h"])
- source_files.extend(["natural_messaging.cc"])
-
- # TODO(fxbug.dev/108680): Better workaround for skipping codegen for zx.
- if name == "zx":
- source_files = ["markers.h"]
-
- for header in header_files:
- headers.append(context.actions.declare_file(dir + "/" + header))
- for source in source_files:
- sources.append(context.actions.declare_file(dir + "/" + source))
-
- else: # context.attr.binding_level == "hlcpp"
- dir = base_path + "/" + name.replace(".", "/") + "/cpp"
- headers.append(context.actions.declare_file(dir + "/fidl.h"))
- headers.append(context.actions.declare_file(dir + "/fidl_test_base.h"))
- sources.append(context.actions.declare_file(dir + "/fidl.cc"))
-
- outputs = [root] + headers + sources
- context.actions.run(
- executable = fidlgen,
- arguments = [
- "--json",
- ir.path,
- "--root",
- root.path,
- ],
- inputs = [
- ir,
- ],
- outputs = outputs,
- mnemonic = "FidlGenCc",
- )
-
- return [
- _CodegenInfo(files = depset(sources)),
- DefaultInfo(files = depset(headers)),
- ]
-
-def _impl_wrapper_impl(context):
- files = context.attr.codegen[_CodegenInfo].files
- return [DefaultInfo(files = files)]
-
-# Runs fidlgen to produce both the header file and the implementation file.
-# Only exposes the header as a source, as the two files need to be consumed by
-# the cc_library as two separate rules.
-_codegen = rule(
- implementation = _codegen_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- # Files must be generated in genfiles in order for the header to be included
- # anywhere.
- output_to_genfiles = True,
- attrs = {
- "library": attr.label(
- doc = "The FIDL library to generate code for",
- mandatory = True,
- allow_files = False,
- providers = [FuchsiaFidlLibraryInfo],
- ),
- "binding_level": attr.string(
- doc = "Controls whether to generate high- (hlcpp) or low-level (llcpp) C++ bindings.",
- mandatory = True,
- ),
- },
-)
-
-# Simply declares the implementation file generated by the codegen target as an
-# output.
-# This allows the implementation file to be exposed as a source in its own rule.
-_impl_wrapper = rule(
- implementation = _impl_wrapper_impl,
- output_to_genfiles = True,
- attrs = {
- "codegen": attr.label(
- doc = "The codegen rules generating the implementation file",
- mandatory = True,
- allow_files = False,
- providers = [_CodegenInfo],
- ),
- },
-)
-
-def _fidl_cc_library(name, library, binding_level, deps = [], tags = [], **kwargs):
- """Generates cc_library() for the given fidl_library.
-
- Args:
- name: Target name. Required.
- library: fidl_library() target to generate the language bindings for. Required.
- binding_level: Controls whether to generate high- (hlcpp) or low-level (llcpp) C++ bindings.
- deps: Additional dependencies.
- tags: Optional tags.
- **kwargs: Remaining args.
- """
- gen_name = "%s_codegen" % name
- impl_name = "%s_impl" % name
-
- _codegen(
- name = gen_name,
- library = library,
- binding_level = binding_level,
- )
-
- _impl_wrapper(
- name = impl_name,
- codegen = ":%s" % gen_name,
- )
-
- native.cc_library(
- name = name,
- hdrs = [
- ":%s" % gen_name,
- ],
- srcs = [
- ":%s" % impl_name,
- # For the coding tables.
- library,
- ],
- # This is necessary in order to locate generated headers.
- strip_include_prefix = gen_name + "." + binding_level,
- deps = deps,
- tags = tags,
- **kwargs
- )
-
-def fuchsia_fidl_hlcpp_library(name, library, deps = [], tags = [], **kwargs):
- """Generates HLCPP cc_library() for the given fidl_library.
-
- DEPRECATED: use fuchsia_fidl_library instead.
-
- Args:
- name: Target name. Required.
- library: fidl_library() target to generate the language bindings for. Required.
- deps: Additional dependencies.
- tags: Optional tags.
- **kwargs: Remaining args.
- """
- _fidl_cc_library(
- tags = tags,
- name = name,
- library = library,
- binding_level = "hlcpp",
- deps = deps,
- **kwargs
- )
-
-def fuchsia_fidl_llcpp_library(name, library, deps = [], tags = [], **kwargs):
- """Generates LLCPP cc_library() for the given fidl_library.
-
- DEPRECATED: use fuchsia_fidl_library instead.
-
- Args:
- name: Target name. Required.
- library: fidl_library() target to generate the language bindings for. Required.
- deps: Additional dependencies.
- tags: Optional tags.
- **kwargs: Remaining args.
- """
- _fidl_cc_library(
- tags = tags,
- name = name,
- library = library,
- binding_level = "llcpp",
- deps = deps,
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/licenses/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/private/licenses/BUILD.bazel
deleted file mode 100644
index 9088fb9..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/licenses/BUILD.bazel
+++ /dev/null
@@ -1,16 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-exports_files(
- glob([
- "*.bzl",
- ]),
- visibility = ["//:__subpackages__"],
-)
-
-filegroup(
- name = "all_starlark_files",
- srcs = glob(["*.bzl"]),
- visibility = ["//:__subpackages__"],
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_classification.bzl b/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_classification.bzl
deleted file mode 100644
index 3a56f09..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_classification.bzl
+++ /dev/null
@@ -1,131 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for classifying OSS licenses."""
-
-def _fuchsia_licenses_classification_impl(ctx):
- out_json = ctx.actions.declare_file(ctx.label.name)
-
- inputs = [ctx.file.spdx_input, ctx.executable.identify_license]
- arguments = [
- "--spdx_input=%s" % ctx.file.spdx_input.path,
- "--identify_license_bin=%s" % ctx.executable.identify_license.path,
- "--output_file=%s" % out_json.path,
- ]
-
- if ctx.file.conditions_policy:
- inputs.append(ctx.file.conditions_policy)
- arguments.append("--conditions_policy=%s" % ctx.file.conditions_policy.path)
- if ctx.attr.default_condition:
- arguments.append("--default_condition=%s" % ctx.attr.default_condition)
- if ctx.attr.allowed_conditions:
- arguments.append("--allowed_conditions")
- arguments.extend(ctx.attr.allowed_conditions)
- if ctx.attr.fail_on_disallowed_conditions:
- arguments.append("--fail_on_disallowed_conditions=True")
- if ctx.files.policy_override_rules:
- inputs.extend(ctx.files.policy_override_rules)
- arguments.append("--policy_override_rules")
- arguments.extend([f.path for f in ctx.files.policy_override_rules])
-
- ctx.actions.run(
- progress_message = "Generating license classifications into %s" % out_json.path,
- inputs = inputs,
- outputs = [out_json],
- executable = ctx.executable._generate_licenses_classification_tool,
- arguments = arguments,
- )
-
- return [DefaultInfo(files = depset([out_json]))]
-
-fuchsia_licenses_classification = rule(
- doc = """
-Produces a json file with license classification output.
-
-The [name].json has the following schema:
-
-```
-{
- // Dictionary of license_ids : lists of classifcations
- "[license_id]":
- [
- // list of named classsifications
- {
- "name": str,
- "confidence": float,
- "start_line": int,
- "end_line": int,
- },
- ...
- ],
- ,
- ...
-}
-```
-""",
- implementation = _fuchsia_licenses_classification_impl,
- attrs = {
- "spdx_input": attr.label(
- doc = "The target to aggregate the licenses from.",
- allow_single_file = True,
- mandatory = True,
- ),
- "identify_license": attr.label(
- doc = """The location of the 'identify_license' tool from
-https://github.com/google/licenseclassifier/tree/main/tools/identify_license
-or a program with a similar I/O. Different organizations should configure
-and build identify_license to match their organization OSS compliance policies.
-""",
- executable = True,
- cfg = "exec",
- mandatory = True,
- ),
- "conditions_policy": attr.label(
- doc = """A CSV file that maps license identification names to conditions.
-License snippets identified with the given name will be applied the
-given 'condition'. The CSV should have 2 columns: 'license', 'condition'.
-The rows should map a license identification name to a condition.
-
-For example:
-```
-license,condition
-MIT, allowed
-GPL, forbidden
-foo, bar
-```
-
-The specific conditions and their meanings are organization specific.
-""",
- allow_single_file = True,
- mandatory = False,
- default = None,
- ),
- "policy_override_rules": attr.label_list(
- doc = """Condition override rule files""",
- allow_files = True,
- mandatory = False,
- default = [],
- ),
- "default_condition": attr.string(
- doc = "The default condition for unmapped or unidentified licenses",
- mandatory = False,
- default = "",
- ),
- "allowed_conditions": attr.string_list(
- doc = """List of allowed conditions.""",
- mandatory = False,
- default = [],
- ),
- "fail_on_disallowed_conditions": attr.bool(
- doc = """The rule will fail if identified licenses map to disallowed conditions.""",
- mandatory = False,
- default = False,
- ),
- "_generate_licenses_classification_tool": attr.label(
- executable = True,
- cfg = "exec",
- default = "//fuchsia/tools/licenses:generate_licenses_classification",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_notice.bzl b/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_notice.bzl
deleted file mode 100644
index a0707df..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_notice.bzl
+++ /dev/null
@@ -1,40 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for generating OSS licenses license notice text file."""
-
-def _fuchsia_licenses_notice(ctx):
- notice_file = ctx.actions.declare_file("%s" % ctx.attr.name)
-
- ctx.actions.run(
- progress_message = "Generating licenses notice file %s" % notice_file.path,
- inputs = [ctx.file.spdx_input],
- outputs = [notice_file],
- executable = ctx.executable._generate_licenses_notice_tool,
- arguments = [
- "--spdx_input=%s" % ctx.file.spdx_input.path,
- "--output_file=%s" % notice_file.path,
- ],
- )
-
- return [DefaultInfo(files = depset([notice_file]))]
-
-fuchsia_licenses_notice = rule(
- doc = """
-Produces a licenses notice text file from the given SPDX file.
-""",
- implementation = _fuchsia_licenses_notice,
- attrs = {
- "spdx_input": attr.label(
- doc = "The target to aggregate the licenses from.",
- allow_single_file = True,
- mandatory = True,
- ),
- "_generate_licenses_notice_tool": attr.label(
- executable = True,
- cfg = "exec",
- default = "//fuchsia/tools/licenses:generate_licenses_notice",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_review.bzl b/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_review.bzl
deleted file mode 100644
index dbc0fb8..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_review.bzl
+++ /dev/null
@@ -1,68 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for generating OSS licenses compliance materials."""
-
-def _fuchsia_licenses_review(ctx):
- out_dir = ctx.actions.declare_directory(ctx.label.name + ".unzipped")
- out_zip = ctx.actions.declare_file(ctx.label.name)
-
- run_inputs = [ctx.file.spdx_input]
- run_arguments = [
- "--spdx_input=%s" % ctx.file.spdx_input.path,
- "--output_dir=%s" % out_dir.path,
- "--output_file=%s" % out_zip.path,
- ]
-
- if ctx.file.classification_input:
- run_inputs.append(ctx.file.classification_input)
- run_arguments.append("--classification_input=%s" % ctx.file.classification_input.path)
-
- ctx.actions.run(
- progress_message = "Generating license review material into %s" % out_dir.path,
- inputs = run_inputs,
- outputs = [out_dir, out_zip],
- executable = ctx.executable._generate_licenses_review_tool,
- arguments = run_arguments,
- )
-
- return [DefaultInfo(files = depset([out_zip]), runfiles = ctx.runfiles([out_zip]))]
-
-fuchsia_licenses_review = rule(
- doc = """
-Produces a zip file with [name] containing license review material.
-
-The file contains:
-
- + summary.csv
- + licenses.spdx.json
- + classifications.json (optional)
- + extracted_licenses (directory)
- + LicenseRef-1.txt
- + LicenseRef-2.txt
- + LicenseRef-3.txt
- + ...
- + (A txt file with the contents of each extracted license)
-
-The SPDX json conforms with:
-https://github.com/spdx/spdx-spec/blob/master/schemas/spdx-schema.json
-""",
- implementation = _fuchsia_licenses_review,
- attrs = {
- "spdx_input": attr.label(
- doc = "The output of `fuchsia_licenses_spdx` invocation.",
- allow_single_file = True,
- mandatory = True,
- ),
- "classification_input": attr.label(
- doc = "The output of `fuchsia_licenses_classification` invocation (optional).",
- allow_single_file = True,
- ),
- "_generate_licenses_review_tool": attr.label(
- executable = True,
- cfg = "exec",
- default = "//fuchsia/tools/licenses:generate_licenses_review",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_spdx.bzl b/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_spdx.bzl
deleted file mode 100644
index 62f10d4..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/licenses/fuchsia_licenses_spdx.bzl
+++ /dev/null
@@ -1,95 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Rule for license aggregation in SPDX generation."""
-
-load(
- "@rules_license//rules:gather_licenses_info.bzl",
- "gather_licenses_info",
- "write_licenses_info",
-)
-load(
- "@rules_license//rules:providers.bzl",
- "TransitiveLicensesInfo",
-)
-
-# Debugging verbosity. Set to >0 for debugging
-_VERBOSITY = 0
-
-def _debug(loglevel, msg):
- if _VERBOSITY > loglevel:
- print(msg) # buildifier: disable=print
-
-def _fuchsia_licenses_spdx_impl(ctx):
- _debug(0, "_fuchsia_licenses_spdx_impl")
-
- license_infos = []
- license_files = []
- if TransitiveLicensesInfo in ctx.attr.target:
- license_infos = ctx.attr.target[TransitiveLicensesInfo].licenses.to_list()
- for info in license_infos:
- license_files.append(info.license_text)
- _debug(0, "Found %s license infos: %s" % (len(license_infos), license_infos))
-
- licenses_used_file = ctx.actions.declare_file("%s.licenses_used.json" % ctx.attr.name)
-
- write_licenses_info(
- ctx,
- deps = [ctx.attr.target],
- json_out = licenses_used_file,
- )
-
- spdx_output = ctx.actions.declare_file(ctx.attr.name)
-
- ctx.actions.run(
- progress_message = "Generating SPDX from %s into %s" %
- (licenses_used_file.path, spdx_output.path),
- inputs = [licenses_used_file] + license_files,
- outputs = [spdx_output],
- executable = ctx.executable._generate_licenses_spdx_tool,
- arguments = [
- "--licenses_used=%s" % licenses_used_file.path,
- "--spdx_output=%s" % spdx_output.path,
- "--root_package_name=%s" % ctx.attr.target.label.name,
- "--document_namespace=%s" % ctx.attr.document_namespace,
- "--licenses_cross_refs_base_url=%s" % ctx.attr.licenses_cross_refs_base_url,
- ],
- )
-
- return [DefaultInfo(files = depset([spdx_output]))]
-
-fuchsia_licenses_spdx = rule(
- doc = """
-Produces a licenses spdx file for the given target.
-
-This rule generates a licenses SPDX json file for all
-@rules_license://rules:license declarations that the given
-target depends on.
-
-The SPDX json conforms with:
-https://github.com/spdx/spdx-spec/blob/master/schemas/spdx-schema.json
-""",
- implementation = _fuchsia_licenses_spdx_impl,
- attrs = {
- "target": attr.label(
- doc = "The target to aggregate the licenses from.",
- mandatory = True,
- aspects = [gather_licenses_info],
- ),
- "document_namespace": attr.string(
- doc = "A unique namespace url for the SPDX references in the doc",
- mandatory = True,
- ),
- "licenses_cross_refs_base_url": attr.string(
- doc = "Base URL for license paths that are local files",
- mandatory = True,
- default = "",
- ),
- "_generate_licenses_spdx_tool": attr.label(
- executable = True,
- cfg = "exec",
- default = "//fuchsia/tools/licenses:generate_licenses_spdx",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/package_publishing.bzl b/bazel_rules_fuchsia/fuchsia/private/package_publishing.bzl
deleted file mode 100644
index 7990903..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/package_publishing.bzl
+++ /dev/null
@@ -1,66 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load("//fuchsia/private:providers.bzl", "FuchsiaPackageRepoPathInfo")
-
-def package_repo_path_from_label(label):
- if FuchsiaPackageRepoPathInfo in label:
- repo_path = label[FuchsiaPackageRepoPathInfo].path
- return repo_path if repo_path != "" else None
- return None
-
-def publish_package(ctx, pm, repo_path, package_manifests):
- """ Will publish the list of package manifests to the server at repo_path
-
- Args:
- ctx: The rule context
- pm: The pm tool
- repo_path: The path to the package repository
- package_manifests: A list of packages that should be published.
-
- Returns:
- The stamp file indicating that the publishing was succesful
- """
-
- stamp_file = ctx.actions.declare_file(ctx.label.name + "_publish.stamp")
-
- list_of_packages = ctx.actions.declare_file(ctx.label.name + "_packages.list")
- ctx.actions.write(
- output = list_of_packages,
- content = "\n".join([p.path for p in package_manifests]),
- )
-
- # Wrap the publishing in a script which will write to a stamp file. We need
- # to run this in a script instead of an action because `pm publish` does not
- # write to a file and thus Bazel will not run it and we need to write to a
- # repository outside of the Bazel sandbox.
-
- content = """#!/bin/bash
- if [[ ! -d "{repo}" ]]; then
- echo >&2 "WARNING: no repository in {repo}, creating it!"
- {pm} newrepo -repo {repo} || exit 1
- fi
- {pm} publish -n -lp -f {packages} -repo {repo} || exit 1
-
- echo 'SUCCESS' > {stampfile}
- """.format(pm = pm.path, packages = list_of_packages.path, repo = repo_path, stampfile = stamp_file.path)
-
- publish_script = ctx.actions.declare_file(ctx.label.name + "_publish_package.sh")
- ctx.actions.write(
- output = publish_script,
- content = content,
- is_executable = True,
- )
-
- ctx.actions.run(
- executable = publish_script,
- inputs = package_manifests + [list_of_packages],
- outputs = [
- stamp_file,
- ],
- mnemonic = "FuchsiaPmPublish",
- progress_message = "Publishing package for %{target.label}",
- )
-
- return stamp_file
diff --git a/bazel_rules_fuchsia/fuchsia/private/providers.bzl b/bazel_rules_fuchsia/fuchsia/private/providers.bzl
deleted file mode 100644
index 104143d..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/providers.bzl
+++ /dev/null
@@ -1,248 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""All Fuchsia Providers."""
-
-FuchsiaAssembledArtifactInfo = provider(
- "Artifacts that can be included into a product. It consists of the artifact and the corresponding config data.",
- fields = {
- "artifact": "The base artifact",
- "configs": "A list of configs that is attached to artifacts",
- },
-)
-
-FuchsiaConfigData = provider(
- "The config data which is used in assembly.",
- fields = {
- "source": "Config file on host",
- "destination": "A String indicating the path to find the file in the package on the target",
- },
-)
-
-FuchsiaComponentInfo = provider(
- "Contains information about a fuchsia component",
- fields = {
- "name": "name of the component",
- "manifest": "A file representing the compiled component manifest file",
- "resources": "any additional resources the component needs",
- "is_driver": "True if this is a driver",
- "is_test": "True if this is a test component",
- },
-)
-
-FuchsiaDebugSymbolInfo = provider(
- "Contains information that can be used to register debug symbols.",
- fields = {
- "build_id_dirs": "A mapping of build directory to depset of build_id directories.",
- },
-)
-
-FuchsiaUnitTestComponentInfo = provider(
- "Allows unit tests to be treated as test components.",
- fields = {
- "test_component": "The label of the underlying fuchsia_test_component.",
- },
-)
-
-FuchsiaComponentManifestShardInfo = provider(
- "Contains information about a Fuchsia component manifest shard",
- fields = {
- "file": "The file of the shard",
- "base_path": "Base path of the shard, used in includepath argument of cmc compile",
- },
-)
-
-FuchsiaComponentManifestShardCollectionInfo = provider(
- "Contains information about a collection of shards to add as dependencies for for each cmc invocation",
- fields = {
- "shards": "A list of shards's as targets in the collection",
- },
-)
-
-FuchsiaEmulatorInfo = provider(
- "Contains information about a fuchsia emulator.",
- fields = {
- "name": "The name of the emulator",
- "launch_options": "The list of additional options to use when launching",
- },
-)
-
-FuchsiaFidlLibraryInfo = provider(
- "Contains information about a FIDL library",
- fields = {
- "info": "List of structs(name, files) representing the library's dependencies",
- "name": "Name of the FIDL library",
- "ir": "Path to the JSON file with the library's intermediate representation",
- },
-)
-
-FuchsiaBindLibraryInfo = provider(
- "Contains information about a Bind Library.",
- fields = {
- "name": "Name of the Bind Library.",
- "transitive_sources": "A depset containing transitive sources of the Bind Library.",
- },
-)
-
-FuchsiaCoreImageInfo = provider(
- "Private provider containing platform artifacts",
- fields = {
- "esp_blk": "EFI system partition image.",
- "kernel_zbi": "Zircon image.",
- "vbmetar": "vbmeta for zirconr boot image.",
- "zirconr": "zedboot boot image.",
- },
-)
-
-FuchsiaPackageResourcesInfo = provider(
- "Contains a collection of resources to include in a package",
- fields = {
- "resources": "A list of structs containing the src and dest of the resource",
- },
-)
-
-FuchsiaPackageGroupInfo = provider(
- doc = "The raw files that make up a set of fuchsia packages.",
- fields = {
- "packages": "a list of all packages that make up this package group",
- },
-)
-
-FuchsiaPackageInfo = provider(
- doc = "Contains information about a fuchsia package.",
- fields = {
- "package_manifest": "JSON package manifest file representing the Fuchsia package.",
- "package_name": "The name of the package",
- "far_file": "The far archive",
- "meta_far": "The meta.far file",
- "files": "all files that compose this package, including the manifest and meta.far",
- "build_id_dir": "Directory containing the debug symbols",
- "components": "A list of all of the component manifest strings inclusive of driver components.",
- "drivers": "A list of driver manifest strings.",
- "package_resources": "A list of resources added to this package",
- },
-)
-
-FuchsiaProductImageInfo = provider(
- doc = "Info needed to pave a Fuchsia image",
- fields = {
- "esp_blk": "EFI system partition image.",
- "blob_blk": "BlobFS partition image.",
- "data_blk": "MinFS partition image.",
- "images_json": "images.json file",
- "blobs_json": "blobs.json file",
- "kernel_zbi": "Zircon image.",
- "vbmetaa": "vbmeta for zircona boot image.",
- "vbmetar": "vbmeta for zirconr boot image.",
- "zircona": "main boot image.",
- "zirconr": "zedboot boot image.",
- "flash_json": "flash.json file.",
- },
-)
-
-FuchsiaAssemblyConfigInfo = provider(
- doc = "Private provider that includes a single JSON configuration file.",
- fields = {
- "config": "JSON configuration file",
- },
-)
-
-FuchsiaProductAssemblyBundleInfo = provider(
- doc = """
-A bundle of files used by product assembly.
-This should only be provided by the single exported target of a
-fuchsia_product_assembly_bundle repository.
-""",
- fields = {
- "root": "A blank file at the root of the bundle directory",
- "files": "All files contained in the bundle",
- },
-)
-
-FuchsiaProductBundleConfigInfo = provider(
- doc = "Config data used for pbm creation",
- fields = {
- "packages": "Path to packages directory.",
- "images_json": "Path to images.json file.",
- "zbi": "Path to ZBI file.",
- "fvm": "Path to FVM file.",
- },
-)
-
-FuchsiaProvidersInfo = provider(
- doc = """
- Keeps track of what providers exist on a given target.
- Construct with utils.bzl > track_providers.
- Used by utils.bzl > alias.
- """,
- fields = {
- "providers": "A list of providers values to carry forward.",
- },
-)
-
-FuchsiaVersionInfo = provider(
- doc = "version information passed in that overwrite sdk version",
- fields = {
- "version": "The version string.",
- },
-)
-
-AccessTokenInfo = provider(
- doc = "Access token used to upload to MOS repository",
- fields = {
- "token": "The token string.",
- },
-)
-
-FuchsiaPackageRepoPathInfo = provider(
- doc = "A provider which provides the path to a fuchsia package repo",
- fields = {
- "path": "The path to the repository.",
- },
-)
-
-FuchsiaPackageRepoInfo = provider(
- doc = "A provider which provides the contents of a fuchsia package repo",
- fields = {
- "packages": "The paths to the package_manifest.json files",
- "repo_dir": "The directory of the package repo.",
- "blobs": "The blobs needed by packages in this package repo.",
- },
-)
-
-FuchsiaLocalPackageRepositoryInfo = provider(
- doc = "A provider which provides the configuration for a local package repo.",
- fields = {
- "repo_name": "The name of the repository",
- "repo_path": "The path of the repository. If relative it is treated as relative to the workspace root",
- },
-)
-
-FuchsiaRunnableInfo = provider(
- doc = "A provider which provides the script and runfiles to run a Fuchsia component or test package.",
- fields = {
- "executable": "A file corresponding to the runnable script.",
- "runfiles": "A list of runfiles that the runnable script depends on.",
- "is_test": "Whether this runnable is a test.",
- },
-)
-
-FuchsiaDriverToolInfo = provider(
- doc = "A provider which contains information about a driver tool",
- fields = {
- "binary": "A resource struct containing the binary",
- "resources": "A list of all the resources needed by the target",
- },
-)
-
-FuchsiaProductBundleInfo = provider(
- doc = "Product Bundle Info",
- fields = {
- "product_bundle": "The full URL for the product bundle. Can be empty.",
- "is_remote": "Whether the product bundle is a local path or a remote url.",
- "product_name": "The name of the product to be used if product_bundle is empty.",
- "version": "The version of the product to use. If empty use the sdk version.",
- "repository": "The name of the repository to host extra packages in the product bundle",
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/templates/cc_test_manifest.cml b/bazel_rules_fuchsia/fuchsia/private/templates/cc_test_manifest.cml
deleted file mode 100644
index c0394d6..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/templates/cc_test_manifest.cml
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2022 The Fuchsia Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-{
- program: {
- runner: '{{RUNNER}}',
- binary: 'bin/{{BINARY}}',
- },
- capabilities: [
- { protocol: "fuchsia.test.Suite" },
- ],
- expose: [
- {
- protocol: "fuchsia.test.Suite",
- from: "self",
- },
- ],
-}
diff --git a/bazel_rules_fuchsia/fuchsia/private/utils.bzl b/bazel_rules_fuchsia/fuchsia/private/utils.bzl
deleted file mode 100644
index 50759b1..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/utils.bzl
+++ /dev/null
@@ -1,292 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Common utilities needed by rules_fuchsia rules."""
-
-load(
- "@fuchsia_sdk//:workspace_output_base.bzl",
- _WORKSPACE_OUTPUT_BASE = "WORKSPACE_OUTPUT_BASE",
-)
-load(":providers.bzl", "FuchsiaProvidersInfo")
-
-WORKSPACE_OUTPUT_BASE = _WORKSPACE_OUTPUT_BASE
-
-_INVALID_LABEL_CHARACTERS = "\"!%@^_#$&'()*+,;<=>?[]{|}~/".elems()
-
-def normalized_target_name(label):
- label = label.lower()
- for c in _INVALID_LABEL_CHARACTERS:
- label = label.replace(c, ".")
- return label
-
-def label_name(label):
- # convert the label to a single word
- # //foo/bar -> bar
- # :bar -> bar
- # //foo:bar -> bar
- return label.split("/")[-1].split(":")[-1]
-
-def get_project_execroot(ctx):
- # Gets the project/workspace execroot relative to the output base.
- # See https://bazel.build/docs/output_directories.
- return "execroot/%s" % ctx.workspace_name
-
-def get_target_execroot(ctx, target):
- # Gets the execroot for a given target, relative to the project execroot.
- # See https://bazel.build/docs/output_directories.
- return target[DefaultInfo].files_to_run.runfiles_manifest.dirname + "/" + ctx.workspace_name
-
-def stub_executable(ctx):
- """Returns a stub executable that fails with a message."""
- executable_file = ctx.actions.declare_file(ctx.label.name + "_fail.sh")
- content = """#!/bin/bash
- echo "---------------------------------------------------------"
- echo "ERROR: Attempting to run a target or dependency that is not runnable"
- echo "Got {target}"
- echo "---------------------------------------------------------"
- exit 1
- """.format(target = ctx.attr.name)
-
- ctx.actions.write(
- output = executable_file,
- content = content,
- is_executable = True,
- )
-
- return executable_file
-
-def flatten(elements):
- """Flattens an arbitrarily nested list of lists to non-list elements while preserving order."""
- result = []
- unprocessed = list(elements)
- for _ in range(len(str(unprocessed))):
- if not unprocessed:
- return result
- elem = unprocessed.pop(0)
- if type(elem) in ("list", "tuple"):
- unprocessed = list(elem) + unprocessed
- else:
- result.append(elem)
- fail("Unable to flatten list!")
-
-def collect_runfiles(ctx, *elements, ignore_types = []):
- """Collects multiple types of elements (...files, ...targets, ...runfiles) into runfiles."""
-
- # Map to runfiles objects.
- runfiles = []
- for elem in flatten(elements):
- if type(elem) == "Target":
- runfiles.append(elem[DefaultInfo].default_runfiles)
- files_to_run = elem[DefaultInfo].files_to_run
- if files_to_run.executable and files_to_run.runfiles_manifest:
- runfiles.append(ctx.runfiles([
- files_to_run.executable,
- files_to_run.runfiles_manifest,
- ]))
- elif type(elem) == "File":
- runfiles.append(ctx.runfiles([elem]))
- elif type(elem) == "runfiles":
- runfiles.append(elem)
- elif type(elem) not in ignore_types:
- fail("Unable to get runfiles from %s: %s" % (type(elem), str(elem)))
-
- # Merges runfiles for a given target.
- return ctx.runfiles().merge_all(runfiles)
-
-def wrap_executable(ctx, executable, *arguments, script_name = None):
- """Wraps an executable with predefined command line arguments.
-
- Creates a wrapper script that invokes an underlying executable with
- predefined command line arguments.
-
- script_name defaults to `run_${target_name}.sh`.
- """
- wrapper = ctx.actions.declare_file(script_name or "run_%s.sh" % ctx.attr.name)
-
- # Convert file arguments into strings and serialize arguments.
- def serialize(arg):
- readlink = False
- if type(arg) == "Target":
- arg = arg[DefaultInfo].files_to_run.executable
- readlink = True
- if type(arg) == "File":
- arg = arg.short_path
- arg = "'%s'" % arg.replace("'", "\\'")
-
- # Follow symlink for complex tool executables, otherwise we will run
- # into issues with nested runfiles symlink farms.
- if readlink:
- arg = "$(readlink -f %s)" % arg
- return arg
-
- command = [serialize(arg) for arg in [executable] + list(arguments)]
-
- ctx.actions.write(wrapper, """#!/bin/bash
-%s $@
-""" % " ".join(command), is_executable = True)
- return wrapper, collect_runfiles(ctx, executable, arguments, ignore_types = ["string"])
-
-def _add_providers_info(implementation):
- def _impl(ctx):
- return track_providers(implementation(ctx))
-
- return _impl
-
-def _add_default_executable(implementation):
- def _impl(ctx):
- providers = implementation(ctx)
- if not [provider for provider in providers if type(provider) == "DefaultInfo"]:
- providers.append(DefaultInfo(executable = stub_executable(ctx)))
- return providers
-
- return _impl
-
-def rule_variants(implementation, variants = [], attrs = {}, **rule_kwargs):
- """Creates variants of a rule.
-
- Valid variants:
- - None: Behaves like `rule` natively.
- - "executable": Sets executable = True and adds a stub executable if
- DefaultInfo is not provided by implementation.
- - "test": Sets test = True and adds a stub executable if DefaultInfo is not
- provided by implementation.
-
- All other arguments will be forwarded to rule.
- """
- return [rule(
- executable = variant == "executable",
- test = variant == "test",
- attrs = dict(attrs, _variant = attr.string(default = variant or "")),
- implementation = _add_providers_info(
- implementation if variant == None else _add_default_executable(implementation),
- ),
- **rule_kwargs
- ) for variant in variants]
-
-def rule_variant(implementation, variant = None, attrs = {}, **rule_kwargs):
- """Creates a variant of a rule. See rule_variants for argument descriptions."""
- return rule_variants(variants = [variant], attrs = attrs, implementation = implementation, **rule_kwargs)[0]
-
-def track_providers(providers):
- return providers + [FuchsiaProvidersInfo(
- providers = [
- provider
- for provider in providers
- if type(provider) != "DefaultInfo"
- ],
- )]
-
-def forward_providers(ctx, target, *providers, rename_executable = None):
- default_info = target[DefaultInfo]
- if default_info.files_to_run and default_info.files_to_run.executable:
- executable = default_info.files_to_run.executable
- executable_symlink = ctx.actions.declare_file(
- rename_executable or "_" + executable.basename,
- )
- ctx.actions.symlink(
- output = executable_symlink,
- target_file = executable,
- is_executable = True,
- )
- default_info = DefaultInfo(
- files = depset([executable_symlink] + [
- file
- for file in default_info.files.to_list()
- if file != executable
- ]) if rename_executable else default_info.files,
- runfiles = default_info.default_runfiles,
- executable = executable_symlink,
- )
- target_provider_info = target[FuchsiaProvidersInfo] if (
- FuchsiaProvidersInfo in target
- ) else struct(providers = [])
- return [
- target[Provider]
- for Provider in providers
- if Provider in target
- ] + target_provider_info.providers + [default_info]
-
-def _forward_providers(ctx):
- return forward_providers(ctx, ctx.attr.actual)
-
-_alias, _alias_for_executable, _alias_for_test = rule_variants(
- variants = (None, "executable", "test"),
- implementation = _forward_providers,
- attrs = {
- "actual": attr.label(
- doc = "The test workflow entity target to alias.",
- providers = [FuchsiaProvidersInfo],
- mandatory = True,
- ),
- },
-)
-
-def alias(*, name, executable, testonly = False, **kwargs):
- """
- We have to create our own alias macro because Bazel is unreasonable:
- https://github.com/bazelbuild/bazel/issues/10893
-
- The underlying target must be created with `rule_variant(s)` or manually
- include `FuchsiaProvidersInfo` in order to forward providers.
- """
- return ((
- _alias_for_test if testonly else _alias_for_executable
- ) if executable else _alias)(
- name = name,
- testonly = testonly,
- **kwargs
- )
-
-def filter(obj, value = None, exclude = True):
- """Recursively removes matching fields/elements from an object by mutating."""
- if type(obj) not in ("dict", "list"):
- fail("Unsupported data type.")
-
- nested_fields = [obj]
-
- # Since dictionaries and lists can be represented as DAGs, this represents
- # one filter operation within an iterative BFS.
- def filter_next():
- obj = nested_fields.pop(0)
-
- # Lists and dictionaries can both be represented as key-value pairs.
- for k, nested in (obj.items() if type(obj) == "dict" else enumerate(obj)):
- if type(nested) in ("dict", "list"):
- # Add a nested object to the BFS queue.
- nested_fields.append(nested)
- elif (nested == value) == exclude:
- # Remove the matching value's field by mutating the object.
- obj.pop(k)
-
- # Using and iterative BFS to filter all matching values within `obj` should
- # take less than `len(str(obj))` iterations.
- for _ in range(len(str(obj))):
- # Empty nested_fields means that we're done with our BFS.
- if not nested_fields:
- return obj
- filter_next()
-
- # In case the previous assumption is violated.
- fail("Unable to filter all none values!")
-
-def make_resource_struct(src, dest):
- return struct(
- src = src,
- dest = dest,
- )
-
-def get_runfiles(target):
- # Helper function to get the runfiles as a list of files from a target.
- return [symlink.target_file for symlink in target[DefaultInfo].default_runfiles.root_symlinks.to_list()]
-
-# Libs all end with .so or .so followed by a semantic version.
-# Examples: libname.so, libname.so.1, libname.so.1.1
-def is_lib(file):
- rparts = file.basename.rpartition(".so")
- if (rparts[1] != ".so"):
- return False
- for char in rparts[2].elems():
- if not (char.isdigit() or char == "."):
- return False
- return True
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/private/workflows/BUILD.bazel
deleted file mode 100644
index fb5fed3..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/BUILD.bazel
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-exports_files(
- glob([
- "*.bzl",
- ]),
- visibility = ["//:__subpackages__"],
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_development_configuration.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_development_configuration.bzl
deleted file mode 100644
index b5b773a..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_development_configuration.bzl
+++ /dev/null
@@ -1,408 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":fuchsia_task_ffx.bzl", "fuchsia_task_ffx")
-load(
- "//fuchsia/private/workflows:fuchsia_workflow.bzl",
- "fuchsia_workflow",
-)
-load(
- "@rules_fuchsia//fuchsia/private/workflows:fuchsia_task_autodetect_target.bzl",
- "fuchsia_task_autodetect_target",
-)
-load(
- "@rules_fuchsia//fuchsia/private/workflows:fuchsia_package_repository_tasks.bzl",
- "fuchsia_task_repository_register_with_default_target",
-)
-load(
- "//fuchsia/private/workflows:fuchsia_emulator_tasks.bzl",
- "fuchsia_task_emulator_register_repository",
-)
-load("//fuchsia/private/workflows:fuchsia_task_verbs.bzl", "verbs")
-load(
- "//fuchsia/private:providers.bzl",
- "FuchsiaEmulatorInfo",
- "FuchsiaLocalPackageRepositoryInfo",
- "FuchsiaProductBundleInfo",
-)
-load("//fuchsia/private/workflows:fuchsia_shell_task.bzl", "shell_task_rule")
-load(":utils.bzl", "full_product_bundle_url")
-
-def _filter_empty(tasks):
- return [t for t in tasks if t]
-
-def fuchsia_development_configuration(
- name,
- preflight_tasks = None,
- postflight_tasks = None,
- package_repository = None,
- product_bundle = None,
- stop_emulators = False,
- autodetect_target = False,
- emulator = None):
- """Creates a configuration which can be used to prepare a development environment
-
- The development configuration is a target which describes how a user wants
- to setup their development environment for a given target. A user can call
- `bazel run :my_config` to set defaults and tear down old state.
-
- Checking the status of your environment:
- The status of a development environment can be checked by running the command
- `bazel run <name>.status`
- This command will query your system to see if the environment matches the expected
- environment.
-
- Args:
- name: The target name
- preflight_tasks: Any fuchsia_tasks which will run at the beginning of the workflow
- postflight_tasks: Any fuchsia_tasks which will run at the end of the workflow
- package_repository: A fuchsia_local package repository which will be created and
- made the default repository for publishing packages.
- product_bundle: A product bundle which will be fetched and registered with the
- target.
- stop_emulators: If True, all emulators will be stopped before this workflow runs.
- autodetect_target: If True, will attempt to automatically detect the default target.
- emulator: If provided, the emulator will be started and made the default target.
- """
- if autodetect_target:
- if emulator:
- fail("Development Configurations cannot launch an emulator and autodetect a target")
- if not product_bundle:
- fail("Development Configurations cannot autodetect a target without a product bundle")
-
- _status_check_task(
- name = name + ".status",
- emulator = emulator,
- package_repo = package_repository,
- product_bundle = product_bundle,
- )
-
- preflight_workflow = _pre_postflight_workflow(name, preflight_tasks, "preflight")
- pb_workflow = _product_bundle_workflow(product_bundle)
- emulator_workflow = _emulator_workflow(name, emulator, package_repository)
- autodetect_workflow = _autodetect_workflow(name, autodetect_target, package_repository, product_bundle)
- package_repo_workflow = _package_repository_workflow(name, package_repository)
- set_defaults_workflow = _set_defaults_workflow(name, emulator, package_repository)
- postflight_worfklow = _pre_postflight_workflow(name, postflight_tasks, "postflight")
-
- stop_emulators_task = None
- if stop_emulators:
- stop_emulators_task = name + ".stop_emulators"
- fuchsia_task_ffx(
- name = stop_emulators_task,
- arguments = [
- "emu",
- "stop",
- "--all",
- ],
- )
-
- # Start the package server
- start_server_task = name + ".start_package_server"
- _start_server_if_needed(
- name = start_server_task,
- )
-
- summary_task = name + ".summary"
- _summary_task(
- name = summary_task,
- product_bundle = product_bundle,
- emulator = emulator,
- package_repository = package_repository,
- )
-
- sequence = _filter_empty([
- stop_emulators_task,
- start_server_task,
- preflight_workflow,
- pb_workflow,
- package_repo_workflow,
- emulator_workflow,
- autodetect_workflow,
- # We need to set the defaults in their own workflow. This works around
- # an issue where ffx might not actually set the defaults.
- set_defaults_workflow,
- postflight_worfklow,
- summary_task,
- ])
-
- fuchsia_workflow(
- name = name,
- sequence = sequence,
- )
-
-def _summary_task_impl(ctx, make_shell_task):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
-
- summary_lines = [
- "-- Development Configuration Prepared --",
- "Using SDK Version: {}".format(sdk.sdk_id),
- "",
- ]
-
- if ctx.attr.product_bundle:
- pb_info = ctx.attr.product_bundle[FuchsiaProductBundleInfo]
- summary_lines.extend([
- "Product Bundle Summary:",
- " - is_remote = {}".format("True" if pb_info.is_remote else "False"),
- " - full URL: {}".format(full_product_bundle_url(ctx, pb_info)),
- " - local repository: {}".format(pb_info.repository),
- "",
- ])
-
- if ctx.attr.emulator:
- emulator_info = ctx.attr.emulator[FuchsiaEmulatorInfo]
- launch_options = [" {}".format(o) for o in emulator_info.launch_options]
- summary_lines.extend([
- "Emulator Summary:",
- " - name = {}".format(emulator_info.name),
- " - launch options:{}".format(",".join(launch_options)),
- "",
- ])
-
- if ctx.attr.package_repository:
- repo_info = ctx.attr.package_repository[FuchsiaLocalPackageRepositoryInfo]
- summary_lines.extend([
- "Package Repository Summary:",
- " - name = {}".format(repo_info.repo_name),
- " - path = {}".format(repo_info.repo_path),
- "",
- ])
-
- summary_text = ctx.actions.declare_file(ctx.label.name + ".summary_text")
- ctx.actions.write(
- output = summary_text,
- content = "\n".join(summary_lines) + "\n",
- )
-
- # Look into writing a script file for clang and then doing run
- clang_version = ctx.actions.declare_file(ctx.label.name + ".clang_version")
- ctx.actions.run_shell(
- outputs = [clang_version],
- tools = [ctx.executable._clang_bin],
- command = "%s --version > %s" %
- (ctx.executable._clang_bin.path, clang_version.path),
- )
-
- return make_shell_task(
- command = [
- "cat",
- summary_text,
- "&&",
- "echo",
- "Clang Version: ",
- "&&",
- "cat",
- clang_version,
- ],
- )
-
-(__summary_task, _summary_task_for_test, _summary_task) = shell_task_rule(
- implementation = _summary_task_impl,
- toolchains = [
- "@rules_fuchsia//fuchsia:toolchain",
- ],
- attrs = {
- "product_bundle": attr.label(providers = [[FuchsiaProductBundleInfo]]),
- "package_repository": attr.label(providers = [[FuchsiaLocalPackageRepositoryInfo]]),
- "emulator": attr.label(providers = [[FuchsiaEmulatorInfo]]),
- #TODO: don't require the clang binary.
- "_clang_bin": attr.label(
- default = "@fuchsia_clang//:bin/clang",
- executable = True,
- cfg = "exec",
- allow_single_file = True,
- ),
- },
-)
-
-def _pre_postflight_workflow(name, tasks, short_name):
- if not tasks or len(tasks) == 0:
- return None
-
- workflow_name = name + "." + short_name
-
- fuchsia_workflow(
- name = workflow_name,
- sequence = tasks,
- )
- return workflow_name
-
-def _product_bundle_workflow(product_bundle):
- if not product_bundle:
- return None
- return verbs.fetch(product_bundle)
-
-def _emulator_workflow(name, emulator, package_repository):
- if not emulator:
- return None
-
- workflow_name = name + ".emulator"
- sequence = [
- verbs.stop(emulator),
- verbs.start(emulator),
- verbs.wait(emulator),
- ]
-
- if package_repository:
- # Register the repo with the emulator
- register_task = name + ".register_package_repository"
- fuchsia_task_emulator_register_repository(
- name = register_task,
- repository = package_repository,
- emulator = emulator,
- )
- sequence.append(register_task)
-
- fuchsia_workflow(
- name = workflow_name,
- sequence = sequence,
- )
-
- return workflow_name
-
-def _autodetect_workflow(name, autodetect_target, package_repository, product_bundle):
- # Check preconditions
- if not autodetect_target:
- return None
-
- workflow_name = name + ".autodetect"
- fuchsia_task_autodetect_target(
- name = workflow_name,
- product_bundle = product_bundle,
- package_repo = package_repository,
- )
-
- return workflow_name
-
-def _package_repository_workflow(name, package_repo):
- if not package_repo:
- return None
-
- workflow_name = name + ".package_repository"
- sequence = [
- verbs.delete(package_repo),
- verbs.create(package_repo),
- ]
-
- fuchsia_workflow(
- name = workflow_name,
- sequence = sequence,
- )
-
- return workflow_name
-
-def _set_defaults_workflow(name, emulator, package_repo):
- sequence = []
- if emulator:
- sequence.append(verbs.make_default(emulator))
-
- if package_repo:
- sequence.append(verbs.make_default(package_repo))
-
- if len(sequence) > 0:
- workflow_name = name + ".set_defaults"
- fuchsia_workflow(
- name = workflow_name,
- sequence = sequence,
- )
-
- return workflow_name
- else:
- return None
-
-def _start_server_if_needed_impl(ctx, make_shell_task):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- return make_shell_task(
- command = [
- "[[",
- "$(",
- sdk.ffx,
- "config",
- "get",
- "repository.server.enabled",
- ")",
- "!=",
- "'true'",
- "]]",
- "&&",
- sdk.ffx,
- "repository",
- "server",
- "start",
- "||",
- "true",
- ],
- )
-
-(
- __start_server_if_needed,
- _start_server_if_needed_for_test,
- _start_server_if_needed,
-) = shell_task_rule(
- implementation = _start_server_if_needed_impl,
- toolchains = [
- "@rules_fuchsia//fuchsia:toolchain",
- ],
-)
-
-def _status_check_task_impl(ctx, make_shell_task):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- extra_args = []
- if ctx.attr.emulator:
- extra_args.extend([
- "--expected_emulator",
- ctx.attr.emulator[FuchsiaEmulatorInfo].name,
- ])
-
- if ctx.attr.package_repo:
- extra_args.extend([
- "--expected_package_repo",
- ctx.attr.package_repo[FuchsiaLocalPackageRepositoryInfo].repo_name,
- ])
-
- if ctx.attr.product_bundle:
- pb_info = ctx.attr.product_bundle[FuchsiaProductBundleInfo]
- extra_args.extend([
- "--expected_product_bundle",
- full_product_bundle_url(ctx, pb_info),
- "--expected_product_bundle_repo",
- pb_info.repository,
- "--expected_sdk_version",
- pb_info.version or ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"].sdk_id,
- "--expected_product_name",
- pb_info.product_name,
- ])
-
- return make_shell_task(
- command = [
- ctx.attr._development_status_tool,
- "--ffx",
- sdk.ffx,
- "--name",
- str(ctx.label).replace(".status", ""),
- ] + extra_args,
- )
-
-(
- __status_check_task,
- _status_check_task_for_test,
- _status_check_task,
-) = shell_task_rule(
- implementation = _status_check_task_impl,
- toolchains = [
- "@rules_fuchsia//fuchsia:toolchain",
- ],
- attrs = {
- "emulator": attr.label(providers = [[FuchsiaEmulatorInfo]]),
- "package_repo": attr.label(providers = [[FuchsiaLocalPackageRepositoryInfo]]),
- "product_bundle": attr.label(providers = [[FuchsiaProductBundleInfo]]),
- "_development_status_tool": attr.label(
- default = "//fuchsia/tools:development_status",
- doc = "The tool to dump the status.",
- executable = True,
- cfg = "target",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_emulator_tasks.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_emulator_tasks.bzl
deleted file mode 100644
index 8e85613..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_emulator_tasks.bzl
+++ /dev/null
@@ -1,223 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""ffx emu invokations as workflow tasks."""
-
-load(":providers.bzl", "FuchsiaProductBundleInfo")
-load("//fuchsia/private:providers.bzl", "FuchsiaEmulatorInfo", "FuchsiaLocalPackageRepositoryInfo")
-load(":fuchsia_task_ffx.bzl", "ffx_task_rule")
-load(":utils.bzl", "full_product_bundle_url")
-load(
- ":fuchsia_workflow.bzl",
- "fuchsia_workflow",
-)
-
-def fuchsia_task_start_emulator(name, emulator, product_bundle, **kwargs):
- start_name = name + "_emulator"
- register_name = name + "_register_product_bundle"
-
- _fuchsia_task_start_emulator(
- name = start_name,
- emulator = emulator,
- product_bundle = product_bundle,
- **kwargs
- )
-
- fuchsia_task_emulator_register_repository(
- name = register_name,
- emulator = emulator,
- repository = product_bundle,
- aliases = ["fuchsia.com", "chromium.org"],
- )
-
- fuchsia_workflow(
- name = name,
- sequence = [
- start_name,
- register_name,
- ],
- )
-
-def _fuchsia_task_start_emulator_impl(ctx, _make_ffx_task):
- pb_info = ctx.attr.product_bundle[FuchsiaProductBundleInfo]
- return _make_ffx_task(
- prepend_args = [
- "emu",
- "start",
- full_product_bundle_url(ctx, pb_info),
- "--name",
- ctx.attr.emulator[FuchsiaEmulatorInfo].name,
- ] + ctx.attr.emulator[FuchsiaEmulatorInfo].launch_options,
- )
-
-(
- __fuchsia_task_start_emulator,
- _fuchsia_task_start_emulator_for_test,
- _fuchsia_task_start_emulator,
-) = ffx_task_rule(
- doc = """Start an emulator with a product bundle.""",
- implementation = _fuchsia_task_start_emulator_impl,
- attrs = {
- "emulator": attr.label(
- doc = "The emulator that we are stopping",
- providers = [[FuchsiaEmulatorInfo]],
- mandatory = True,
- ),
- "product_bundle": attr.label(
- doc = "The product bundle to use to start the emulator.",
- providers = [[FuchsiaProductBundleInfo]],
- mandatory = True,
- ),
- },
-)
-
-def _fuchsia_task_stop_emulator_impl(ctx, _make_ffx_task):
- return _make_ffx_task(
- prepend_args = [
- "emu",
- "stop",
- ctx.attr.emulator[FuchsiaEmulatorInfo].name,
- ],
- )
-
-(
- _fuchsia_task_stop_emulator,
- _fuchsia_task_stop_emulator_for_test,
- fuchsia_task_stop_emulator,
-) = ffx_task_rule(
- doc = """Stop an emulator with a given name.""",
- implementation = _fuchsia_task_stop_emulator_impl,
- attrs = {
- "emulator": attr.label(
- doc = "The emulator that we are stopping",
- providers = [[FuchsiaEmulatorInfo]],
- mandatory = True,
- ),
- },
-)
-
-def _fuchsia_task_reboot_emulator_impl(ctx, _make_ffx_task):
- return _make_ffx_task(
- prepend_args = [
- "--target",
- ctx.attr.emulator[FuchsiaEmulatorInfo].name,
- "target",
- "reboot",
- ],
- )
-
-(
- _fuchsia_task_reboot_emulator,
- _fuchsia_task_reboot_emulator_for_test,
- fuchsia_task_reboot_emulator,
-) = ffx_task_rule(
- doc = """Attempts to reboot the emulator.""",
- implementation = _fuchsia_task_reboot_emulator_impl,
- attrs = {
- "emulator": attr.label(
- doc = "The emulator that we are stopping",
- providers = [[FuchsiaEmulatorInfo]],
- mandatory = True,
- ),
- },
-)
-
-def _fuchsia_task_make_default_emulator_impl(ctx, _make_ffx_task):
- return _make_ffx_task(
- prepend_args = [
- "target",
- "default",
- "set",
- ctx.attr.emulator[FuchsiaEmulatorInfo].name,
- ],
- )
-
-(
- _fuchsia_task_make_default_emulator,
- _fuchsia_task_make_default_emulator_for_test,
- fuchsia_task_make_default_emulator,
-) = ffx_task_rule(
- doc = """Makes the emulator the default.""",
- implementation = _fuchsia_task_make_default_emulator_impl,
- attrs = {
- "emulator": attr.label(
- doc = "The emulator.",
- providers = [[FuchsiaEmulatorInfo]],
- mandatory = True,
- ),
- },
-)
-
-def _fuchsia_task_emulator_wait_impl(ctx, _make_ffx_task):
- return _make_ffx_task(
- prepend_args = [
- "--target",
- ctx.attr.emulator[FuchsiaEmulatorInfo].name,
- "target",
- "wait",
- ],
- )
-
-(
- _fuchsia_task_emulator_wait,
- _fuchsia_task_emulator_wait_for_test,
- fuchsia_task_emulator_wait,
-) = ffx_task_rule(
- doc = """Waits for the emulator to come online.""",
- implementation = _fuchsia_task_emulator_wait_impl,
- attrs = {
- "emulator": attr.label(
- doc = "The emulator to register with",
- providers = [[FuchsiaEmulatorInfo]],
- mandatory = True,
- ),
- },
-)
-
-def _fuchsia_task_emulator_register_repository_impl(ctx, _make_ffx_task):
- if FuchsiaLocalPackageRepositoryInfo in ctx.attr.repository:
- repo = ctx.attr.repository[FuchsiaLocalPackageRepositoryInfo].repo_name
- elif FuchsiaProductBundleInfo in ctx.attr.repository:
- repo = ctx.attr.repository[FuchsiaProductBundleInfo].repository
- else:
- fail("Only product bundles and local repositories are supported at this time.")
-
- aliases = []
- for alias in ctx.attr.aliases:
- aliases.extend(["--alias", alias])
-
- return _make_ffx_task(
- prepend_args = [
- "target",
- "repository",
- "register",
- "-r",
- repo,
- ] + aliases,
- )
-
-(
- _fuchsia_task_emulator_register_repository,
- _fuchsia_task_emulator_register_repository_for_test,
- fuchsia_task_emulator_register_repository,
-) = ffx_task_rule(
- doc = """Registers a package server with the emulator.""",
- implementation = _fuchsia_task_emulator_register_repository_impl,
- attrs = {
- "repository": attr.label(
- doc = "The repository that is being controlled",
- providers = [[FuchsiaLocalPackageRepositoryInfo], [FuchsiaProductBundleInfo]],
- mandatory = True,
- ),
- "emulator": attr.label(
- doc = "The emulator to register with",
- providers = [[FuchsiaEmulatorInfo]],
- mandatory = True,
- ),
- "aliases": attr.string_list(
- doc = "The list of aliases for this repository",
- default = [],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_package_repository_tasks.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_package_repository_tasks.bzl
deleted file mode 100644
index beca1bd..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_package_repository_tasks.bzl
+++ /dev/null
@@ -1,209 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""ffx package repository invokations as workflow tasks."""
-
-load(":fuchsia_task_ffx.bzl", "ffx_task_rule")
-load("//fuchsia/private:providers.bzl", "FuchsiaLocalPackageRepositoryInfo", "FuchsiaProductBundleInfo")
-load("//fuchsia/private/workflows:fuchsia_shell_task.bzl", "shell_task_rule")
-
-def _repo_task(ctx, make_shell_task, use_ffx = True, args = []):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
-
- tool = sdk.ffx if use_ffx else sdk.pm
- command = [
- "TOOL=$(readlink -f %s)" % tool.short_path,
- "&&",
- "cd",
- "${BUILD_WORKSPACE_DIRECTORY}",
- "&&",
- "$TOOL",
- ]
-
- return make_shell_task(
- command = command + args,
- runfiles = [tool],
- )
-
-def _fuchsia_task_repository_create_impl(ctx, make_fuchsia_task):
- return _repo_task(
- ctx,
- make_fuchsia_task,
- use_ffx = False,
- args = [
- "newrepo",
- "-vt",
- "-repo",
- ctx.attr.repository[FuchsiaLocalPackageRepositoryInfo].repo_path,
- ],
- )
-
-(
- _fuchsia_task_repository_create,
- _fuchsia_task_repository_create_for_test,
- fuchsia_task_repository_create,
-) = shell_task_rule(
- implementation = _fuchsia_task_repository_create_impl,
- doc = """Creates a package server.""",
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "repository": attr.label(
- doc = "The repository that is being controlled",
- providers = [[FuchsiaLocalPackageRepositoryInfo]],
- mandatory = True,
- ),
- },
-)
-
-def _fuchsia_task_repository_add_from_pm_impl(ctx, make_fuchsia_task):
- repo = ctx.attr.repository[FuchsiaLocalPackageRepositoryInfo]
- return _repo_task(
- ctx,
- make_fuchsia_task,
- use_ffx = True,
- args = [
- "repository",
- "add-from-pm",
- "--repository",
- repo.repo_name,
- repo.repo_path,
- ],
- )
-
-(
- _fuchsia_task_repository_add_from_pm,
- _fuchsia_task_repository_add_from_pm_for_test,
- fuchsia_task_repository_add_from_pm,
-) = shell_task_rule(
- doc = """Adds a pm based repo to ffx.""",
- implementation = _fuchsia_task_repository_add_from_pm_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "repository": attr.label(
- doc = "The repository that is being controlled",
- providers = [[FuchsiaLocalPackageRepositoryInfo]],
- mandatory = True,
- ),
- },
-)
-
-#TODO: Pipe this through some processing to do ffx --machine JSON repository list and get the path
-def _fuchsia_task_repository_delete_impl(ctx, make_shell_task):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- command = [
- ctx.attr._clean_repo,
- "--ffx",
- sdk.ffx,
- "--name",
- ctx.attr.repository_name,
- ]
- if ctx.attr.path:
- command.extend([
- "--fallback_path",
- ctx.attr.path,
- ])
-
- if ctx.attr.preserve_contents:
- command.append("--no-delete_contents")
-
- return make_shell_task(
- command = command,
- )
-
-(
- _fuchsia_task_repository_delete,
- _fuchsia_task_repository_delete_for_test,
- fuchsia_task_repository_delete,
-) = shell_task_rule(
- implementation = _fuchsia_task_repository_delete_impl,
- doc = """deletes a package server.""",
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "repository_name": attr.string(
- doc = "The repository to delete",
- mandatory = True,
- ),
- "path": attr.string(
- doc = "The path to this repository",
- mandatory = False,
- ),
- "preserve_contents": attr.bool(
- doc = "If true, the contents will not be deleted from disk",
- mandatory = False,
- default = False,
- ),
- "_clean_repo": attr.label(
- default = "//fuchsia/tools:clean_repo",
- doc = "The tool to remove the repo.",
- executable = True,
- cfg = "target",
- ),
- },
-)
-
-def _fuchsia_package_repository_make_default_impl(ctx, _make_ffx_task):
- return _make_ffx_task(
- prepend_args = [
- "-c",
- "'ffx_repository=true'",
- "repository",
- "default",
- "set",
- ctx.attr.repository[FuchsiaLocalPackageRepositoryInfo].repo_name,
- ],
- )
-
-(
- _fuchsia_package_repository_make_default,
- _fuchsia_package_repository_make_default_for_test,
- fuchsia_package_repository_make_default,
-) = ffx_task_rule(
- doc = """Makes a package server default.""",
- implementation = _fuchsia_package_repository_make_default_impl,
- attrs = {
- "repository": attr.label(
- doc = "The repository that is being controlled",
- providers = [[FuchsiaLocalPackageRepositoryInfo]],
- mandatory = True,
- ),
- },
-)
-
-def fuchsia_task_repository_register_with_default_target(*, name, testonly = True, **kwargs):
- _fuchsia_task_repository_register_with_default_target(
- name = name,
- testonly = testonly,
- **kwargs
- )
-
-def _fuchsia_task_repository_register_with_default_target_impl(ctx, _make_ffx_task):
- if FuchsiaLocalPackageRepositoryInfo in ctx.attr.repository:
- repo = ctx.attr.repository[FuchsiaLocalPackageRepositoryInfo].repo_name
- elif FuchsiaProductBundleInfo in ctx.attr.repository:
- repo = ctx.attr.repository[FuchsiaProductBundleInfo].repository
- else:
- fail("Only product bundles and local repositories are supported at this time.")
-
- return _make_ffx_task(
- prepend_args = [
- "target",
- "repository",
- "register",
- "--repository",
- repo,
- ],
- )
-
-_fuchsia_task_repository_register_with_default_target = ffx_task_rule(
- doc = """Registers the repo with the default target.""",
- implementation = _fuchsia_task_repository_register_with_default_target_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "repository": attr.label(
- doc = "The repository that is being controlled",
- providers = [[FuchsiaLocalPackageRepositoryInfo], [FuchsiaProductBundleInfo]],
- mandatory = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_package_tasks.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_package_tasks.bzl
deleted file mode 100644
index 57e5c6f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_package_tasks.bzl
+++ /dev/null
@@ -1,304 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load(":fuchsia_shell_task.bzl", "shell_task_rule")
-load(":fuchsia_task_ffx.bzl", "fuchsia_task_ffx")
-load(":fuchsia_task_publish.bzl", "fuchsia_task_publish")
-load(":fuchsia_task_register_debug_symbols.bzl", "fuchsia_task_register_debug_symbols")
-load(":fuchsia_task_run_component.bzl", "fuchsia_task_run_component")
-load(":fuchsia_task_run_driver_tool.bzl", "fuchsia_task_run_driver_tool")
-load(":fuchsia_task_verbs.bzl", "make_help_executable", "verbs")
-load(":fuchsia_workflow.bzl", "fuchsia_workflow", "fuchsia_workflow_rule")
-load(":providers.bzl", "FuchsiaDebugSymbolInfo", "FuchsiaPackageInfo", "FuchsiaWorkflowInfo")
-load(":utils.bzl", "flatten", "label_name", "normalized_target_name")
-
-def _to_verb(label):
- return verbs.custom(label_name(label))
-
-def _fuchsia_package_help_impl(ctx, make_shell_task):
- help = make_help_executable(ctx, dict((
- [(verbs.noverb, "Run all test components within this test package.")] if ctx.attr.is_test and ctx.attr.components else []
- ) + [
- (verbs.help, "Print this help message."),
- (verbs.debug_symbols, "Register this package's debug symbols."),
- (verbs.publish, "Publish this package and register debug symbols."),
- ] + [
- (_to_verb(component), "Publish this package and run '%s' with debug symbols." % component)
- for component in ctx.attr.components
- ] + [
- (_to_verb(tool), "Publish this package and run '%s' with debug symbols" % tool)
- for tool in ctx.attr.tools
- ]), name = ctx.attr.top_level_name)
- return make_shell_task([help])
-
-(
- __fuchsia_package_help,
- _fuchsia_package_help_for_test,
- _fuchsia_package_help,
-) = shell_task_rule(
- implementation = _fuchsia_package_help_impl,
- doc = "Prints valid runnable sub-targets in a package.",
- attrs = {
- "is_test": attr.bool(
- doc = "Whether the package is a test package.",
- mandatory = True,
- ),
- "package": attr.label(
- doc = "The package.",
- providers = [FuchsiaPackageInfo],
- mandatory = True,
- ),
- "components": attr.string_list(
- doc = "The component names.",
- mandatory = True,
- ),
- "tools": attr.string_list(
- doc = "The driver tool names.",
- mandatory = True,
- ),
- "debug_symbols_task": attr.label(
- doc = "The debug symbols task associated with the package.",
- providers = [FuchsiaWorkflowInfo],
- mandatory = True,
- ),
- "publish_task": attr.label(
- doc = "The package publishing task associated with the package.",
- providers = [FuchsiaWorkflowInfo],
- mandatory = True,
- ),
- "top_level_name": attr.string(
- doc = "The top level target name associated with these tasks",
- mandatory = True,
- ),
- },
-)
-
-def _fuchsia_package_default_task_impl(ctx, make_workflow):
- default_workflow = make_workflow(sequence = flatten([
- ctx.attr.debug_symbols_task,
- ctx.attr.publish_task,
- ] + ctx.attr.component_run_tasks + [
- ctx.attr.publish_cleanup_task or [],
- ]) if (
- ctx.attr.is_test and ctx.attr.component_run_tasks
- ) else [ctx.attr.help_task])
- return [
- DefaultInfo(
- files = depset(transitive = [provider.files, ctx.attr.package[DefaultInfo].files]),
- runfiles = provider.default_runfiles,
- executable = provider.files.to_list()[0],
- ) if type(provider) == "DefaultInfo" else provider
- for provider in default_workflow
- ] + [
- ctx.attr.package[FuchsiaPackageInfo],
- ctx.attr.package[FuchsiaDebugSymbolInfo],
- # Expose the generated far file and debug symbols.
- # This is also used in fuchsia.git, see https://fxbug.dev/115699 and
- # https://fxbug.dev/119049.
- OutputGroupInfo(
- far_file = depset([ctx.attr.package[FuchsiaPackageInfo].far_file]),
- build_id_dirs = depset(transitive = ctx.attr.package[FuchsiaDebugSymbolInfo].build_id_dirs.values()),
- ),
- ]
-
-(
- __fuchsia_package_default_task,
- _fuchsia_package_default_task_for_test,
- _fuchsia_package_default_task,
-) = fuchsia_workflow_rule(
- implementation = _fuchsia_package_default_task_impl,
- doc = "Runs all test components for test packages, or prints a help message.",
- attrs = {
- "is_test": attr.bool(
- doc = "Whether the package is a test package.",
- mandatory = True,
- ),
- "help_task": attr.label(
- doc = "The help task describing valid package subtargets.",
- providers = [FuchsiaWorkflowInfo],
- mandatory = True,
- ),
- "debug_symbols_task": attr.label(
- doc = "The debug symbols task associated with the package.",
- providers = [FuchsiaWorkflowInfo],
- mandatory = True,
- ),
- "publish_task": attr.label(
- doc = "The package publishing task associated with the package.",
- providers = [FuchsiaWorkflowInfo],
- mandatory = True,
- ),
- "publish_cleanup_task": attr.label(
- doc = "The package publishing cleanup task associated with the package.",
- providers = [FuchsiaWorkflowInfo],
- ),
- "component_run_tasks": attr.label_list(
- doc = "The component run tasks.",
- providers = [FuchsiaWorkflowInfo],
- mandatory = True,
- ),
- "package": attr.label(
- doc = "The package.",
- providers = [FuchsiaPackageInfo],
- mandatory = True,
- ),
- },
-)
-
-def fuchsia_package_tasks(
- *,
- name,
- package,
- components,
- tools = {},
- is_test = False,
- tags = [],
- package_repository_name = None,
- **kwargs):
- # TODO(fxbug.dev/98996): Use ffx isolation. ffx test run currently needs
- # to access ~/.local/share/Fuchsia/ffx/ or else it crashes.
- top_level_tags = tags + (["no-sandbox", "no-cache"] if is_test else [])
-
- # Mark test children as manual.
- manual_test = ["manual"] if is_test else []
-
- # Override testonly since it's used to determine test vs non-test rule
- # variant selection for workflows.
- kwargs["testonly"] = is_test
-
- # For `bazel run :pkg.debug_symbols`.
- debug_symbols_task = verbs.debug_symbols(name)
- fuchsia_task_register_debug_symbols(
- name = debug_symbols_task,
- deps = [package],
- apply_fuchsia_transition = True,
- tags = top_level_tags,
- **kwargs
- )
-
- # For `bazel run :pkg.publish`.
- publish_task = verbs.publish(name)
- anonymous_publish_task = "%s_anonymous" % publish_task
- anonymous_repo_name = "bazel.%s" % normalized_target_name(anonymous_publish_task)
- fuchsia_task_publish(
- name = anonymous_publish_task,
- packages = [package],
- package_repository_name = package_repository_name or anonymous_repo_name,
- **kwargs
- )
- fuchsia_task_ffx(
- name = verbs.delete_repo(anonymous_publish_task),
- arguments = [
- "repository",
- "remove",
- anonymous_repo_name,
- ],
- **kwargs
- )
- publish_only_task = "%s_only" % publish_task
- fuchsia_task_publish(
- name = publish_only_task,
- packages = [package],
- package_repository_name = package_repository_name,
- **kwargs
- )
- fuchsia_workflow(
- name = publish_task,
- sequence = [
- debug_symbols_task,
- publish_only_task,
- ],
- apply_fuchsia_transition = True,
- tags = top_level_tags,
- **kwargs
- )
-
- # For `bazel run :pkg.help`.
- help_task = verbs.help(name)
- _fuchsia_package_help(
- name = help_task,
- package = package,
- components = components.keys(),
- tools = tools,
- debug_symbols_task = debug_symbols_task,
- publish_task = publish_task,
- top_level_name = name,
- is_test = is_test,
- apply_fuchsia_transition = True,
- tags = top_level_tags,
- **kwargs
- )
-
- # For `bazel run :pkg.component`.
- component_run_tasks = []
- for label, component in components.items():
- component_run_task = _to_verb(label)(name)
- component_run_tasks.append("%s.run_only" % component_run_task)
- fuchsia_task_run_component(
- name = component_run_tasks[-1],
- default_argument_scope = "global",
- repository = package_repository_name or anonymous_repo_name,
- package = package,
- component = component,
- tags = tags,
- **kwargs
- )
-
- fuchsia_workflow(
- name = component_run_task,
- sequence = [
- debug_symbols_task,
- anonymous_publish_task,
- component_run_tasks[-1],
- ] + ([] if package_repository_name else [
- verbs.delete_repo(anonymous_publish_task),
- ]),
- apply_fuchsia_transition = True,
- tags = top_level_tags + manual_test,
- **kwargs
- )
-
- # For `bazel run :pkg.tool`.
- for label, tool in tools.items():
- tool_run_task = _to_verb(label)(name)
- fuchsia_task_run_driver_tool(
- name = "%s.run_only" % tool_run_task,
- default_argument_scope = "global",
- repository = package_repository_name or anonymous_repo_name,
- package = package,
- tool = tool,
- tags = tags,
- **kwargs
- )
-
- fuchsia_workflow(
- name = tool_run_task,
- sequence = [
- debug_symbols_task,
- anonymous_publish_task,
- "%s.run_only" % tool_run_task,
- ] + ([] if package_repository_name else [
- verbs.delete_repo(anonymous_publish_task),
- ]),
- apply_fuchsia_transition = True,
- tags = top_level_tags,
- **kwargs
- )
-
- # For `bazel run :pkg`.
- _fuchsia_package_default_task(
- name = name,
- help_task = help_task,
- debug_symbols_task = debug_symbols_task,
- publish_task = anonymous_publish_task,
- publish_cleanup_task = None if (
- package_repository_name
- ) else verbs.delete_repo(anonymous_publish_task),
- component_run_tasks = component_run_tasks,
- is_test = is_test,
- package = package,
- apply_fuchsia_transition = True,
- tags = top_level_tags,
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_product_bundle_tasks.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_product_bundle_tasks.bzl
deleted file mode 100644
index fcf044c..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_product_bundle_tasks.bzl
+++ /dev/null
@@ -1,83 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""ffx product-bundle get invokation as a workflow task."""
-
-load(":providers.bzl", "FuchsiaProductBundleInfo")
-load(":fuchsia_task_ffx.bzl", "ffx_task_rule")
-load(":utils.bzl", "full_product_bundle_url")
-
-def _fuchsia_task_fetch_product_bundle_impl(ctx, _make_ffx_task):
- pb_info = ctx.attr.product_bundle[FuchsiaProductBundleInfo]
- if not pb_info.is_remote:
- fail("Local product bundles do not need to be fetched.")
- args = [
- "product-bundle",
- "get",
- full_product_bundle_url(ctx, pb_info),
- ]
-
- if pb_info.repository:
- args.extend([
- "--repository",
- pb_info.repository,
- ])
-
- if ctx.attr.force_repository_creation:
- args.append("--force-repo")
-
- return _make_ffx_task(
- prepend_args = args,
- )
-
-(
- _fuchsia_task_fetch_product_bundle,
- _fuchsia_task_fetch_product_bundle_for_test,
- fuchsia_task_fetch_product_bundle,
-) = ffx_task_rule(
- doc = """Fetches a remote product bundle.""",
- implementation = _fuchsia_task_fetch_product_bundle_impl,
- attrs = {
- "product_bundle": attr.label(
- doc = "Product bundle to fetch.",
- providers = [[FuchsiaProductBundleInfo]],
- mandatory = True,
- ),
- "force_repository_creation": attr.bool(
- doc = """If True, will pass --force-repo causing forcing the package
- repository creation even if it already exists.
- """,
- default = True,
- ),
- },
-)
-
-def _fuchsia_task_remove_product_bundle_impl(ctx, _make_ffx_task):
- pb_info = ctx.attr.product_bundle[FuchsiaProductBundleInfo]
- args = [
- "product-bundle",
- "remove",
- full_product_bundle_url(ctx, pb_info),
- "--force",
- ]
-
- return _make_ffx_task(
- prepend_args = args,
- )
-
-(
- _fuchsia_task_remove_product_bundle,
- _fuchsia_task_remove_product_bundle_for_test,
- fuchsia_task_remove_product_bundle,
-) = ffx_task_rule(
- doc = """Removes a downloaded product bundle.""",
- implementation = _fuchsia_task_remove_product_bundle_impl,
- attrs = {
- "product_bundle": attr.label(
- doc = "Product bundle to fetch.",
- providers = [[FuchsiaProductBundleInfo]],
- mandatory = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_shell_task.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_shell_task.bzl
deleted file mode 100644
index f69ab85..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_shell_task.bzl
+++ /dev/null
@@ -1,79 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Task for running a shell command."""
-
-load(":fuchsia_task.bzl", "fuchsia_task_rule")
-
-def shell_task_rule(*, implementation, attrs = {}, **kwargs):
- def _shell_task_impl(ctx, make_fuchsia_task):
- def _make_shell_task(command = [], runfiles = []):
- executable, arguments = (command[0], command[1:]) if command else (None, [])
- if type(executable) == "Target":
- runfiles.append(executable)
- command = [
- executable[DefaultInfo].files_to_run.executable,
- ] + arguments
-
- return make_fuchsia_task(ctx.attr._shell_task_runner, command, runfiles = runfiles)
-
- return implementation(ctx, _make_shell_task)
-
- return fuchsia_task_rule(
- implementation = _shell_task_impl,
- attrs = dict(attrs, **{
- # TODO(chandarren): Support regex capture-and-export stdout as workflow state.
- # "capture_state": attr.string_dict(
- # doc = "Export environment variables (name keys) as matched captured stdout (regex values).",
- # ),
- "_shell_task_runner": attr.label(
- doc = "The task runner used to run shell tasks.",
- default = "//fuchsia/tools:fuchsia_shell_task",
- executable = True,
- cfg = "exec",
- ),
- }),
- **kwargs
- )
-
-def _fuchsia_shell_task_impl(ctx, make_shell_task):
- return make_shell_task([ctx.attr.executable] if ctx.attr.executable else [])
-
-__fuchsia_shell_task, _fuchsia_shell_task_for_test, _fuchsia_shell_task = shell_task_rule(
- doc = """Task for running a shell command.""",
- implementation = _fuchsia_shell_task_impl,
- attrs = {
- "executable": attr.label(
- doc = "Specify a bazel target as the shell executable.",
- ),
- },
-)
-
-def fuchsia_shell_task(
- *,
- command = None,
- target = None,
- arguments = [],
- **kwargs):
- """Creates a shell task.
-
- Args:
- command: The command to execute. May be a string or list of strings.
- Mutually exclusive with `target` and `arguments`.
- target: Optionally specify a bazel target as the executable.
- Mutually exclusive with `command`.
- arguments: A list of command line arguments to pass to `command`.
- Not allowed if `command` is a list.
- **kwargs: Additional arguments to forward to the base task rule.
- """
- if bool(command) == bool(target):
- fail("Argument `command` is mutually exclusive with argument `target`.")
- if type(command) == "list" and arguments:
- fail("Please append any arguments to `command`.")
-
- _fuchsia_shell_task(
- arguments = (command or []) + arguments,
- executable = target,
- **kwargs
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task.bzl
deleted file mode 100644
index da73e75..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task.bzl
+++ /dev/null
@@ -1,51 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Base task rule and utilities."""
-
-load(":workflow_entity.bzl", "workflow_entity_rule")
-load(":providers.bzl", "FuchsiaTaskEntityInfo", "FuchsiaWorkflowInfo")
-
-def fuchsia_task_rule(*, implementation, **kwargs):
- """Starlark higher-order rule for creating task primitives."""
-
- def _fuchsia_task_impl(ctx, make_workflow, collect_arguments):
- def _make_fuchsia_task(task_runner, prepend_args = [], runfiles = []):
- task_args, task_runfiles = collect_arguments(prepend_args, runfiles, task_runner)
- return make_workflow(
- FuchsiaWorkflowInfo(
- entities = {
- ctx.label: FuchsiaTaskEntityInfo(
- task_runner = task_runner[DefaultInfo].files_to_run.executable.short_path,
- args = task_args,
- default_argument_scope = ctx.attr.default_argument_scope,
- ),
- },
- entrypoint = ctx.label,
- ),
- task_runfiles,
- )
-
- return implementation(ctx, _make_fuchsia_task)
-
- return workflow_entity_rule(
- implementation = _fuchsia_task_impl,
- **kwargs
- )
-
-def _fuchsia_task_impl(ctx, make_fuchsia_task):
- return make_fuchsia_task(ctx.attr.task_runner)
-
-_fuchsia_task, _fuchsia_task_for_test, fuchsia_task = fuchsia_task_rule(
- implementation = _fuchsia_task_impl,
- doc = """Build-rule version of `fuchsia_task_rule`.""",
- attrs = {
- "task_runner": attr.label(
- mandatory = True,
- doc = "The task runner used to run this task.",
- executable = True,
- cfg = "exec",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_autodetect_target.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_autodetect_target.bzl
deleted file mode 100644
index 35b020e..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_autodetect_target.bzl
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-load("//fuchsia/private/workflows:fuchsia_shell_task.bzl", "shell_task_rule")
-load(
- "//fuchsia/private:providers.bzl",
- "FuchsiaLocalPackageRepositoryInfo",
- "FuchsiaProductBundleInfo",
-)
-
-def _fuchsia_task_autodetect_target_impl(ctx, make_shell_task):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- command = [
- ctx.attr._detect_tool,
- "--ffx",
- sdk.ffx,
- "--product_bundle",
- ctx.attr.product_bundle[FuchsiaProductBundleInfo].product_name,
- "--product_bundle_repo",
- ctx.attr.product_bundle[FuchsiaProductBundleInfo].repository,
- ]
-
- if ctx.attr.package_repo:
- command.extend([
- "--package_repo",
- ctx.attr.package_repo[FuchsiaLocalPackageRepositoryInfo].repo_name,
- ])
-
- return make_shell_task(
- command = command,
- )
-
-(
- _fuchsia_task_autodetect_target,
- _fuchsia_task_autodetect_target_for_test,
- fuchsia_task_autodetect_target,
-) = shell_task_rule(
- implementation = _fuchsia_task_autodetect_target_impl,
- # doc = """Creates a package server.""",
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "product_bundle": attr.label(
- providers = [[FuchsiaProductBundleInfo]],
- mandatory = True,
- ),
- "package_repo": attr.label(
- providers = [[FuchsiaLocalPackageRepositoryInfo]],
- mandatory = False,
- ),
- "_detect_tool": attr.label(
- default = "//fuchsia/tools:detect_target",
- doc = "The tool to detect the tearget.",
- executable = True,
- cfg = "target",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_ffx.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_ffx.bzl
deleted file mode 100644
index b760f5f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_ffx.bzl
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""ffx invokation as a workflow task."""
-
-load(":fuchsia_shell_task.bzl", "shell_task_rule")
-
-def ffx_task_rule(*, implementation, toolchains = [], **kwargs):
- """Starlark higher-order rule for creating ffx-based tasks."""
-
- def _fuchsia_task_ffx_impl(ctx, make_shell_task):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
-
- def _make_ffx_task(prepend_args = [], *runfiles):
- return make_shell_task([sdk.ffx] + prepend_args, *runfiles)
-
- return implementation(ctx, _make_ffx_task)
-
- return shell_task_rule(
- implementation = _fuchsia_task_ffx_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"] + toolchains,
- **kwargs
- )
-
-def _fuchsia_task_ffx_impl(_, _make_ffx_task):
- return _make_ffx_task()
-
-_fuchsia_task_ffx, _fuchsia_task_ffx_for_test, fuchsia_task_ffx = ffx_task_rule(
- implementation = _fuchsia_task_ffx_impl,
- doc = """Defines a task which invokes ffx.""",
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_flash.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_flash.bzl
deleted file mode 100644
index 3dc7436..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_flash.bzl
+++ /dev/null
@@ -1,30 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Flash device using product bundle as a task workflow."""
-
-load(":providers.bzl", "FuchsiaProductBundleInfo")
-load(":fuchsia_task_ffx.bzl", "ffx_task_rule")
-
-def _fuchsia_task_flash_impl(ctx, _make_ffx_task):
- return _make_ffx_task(
- prepend_args = [
- "target",
- "flash",
- "--product-bundle",
- ctx.attr.product_bundle[FuchsiaProductBundleInfo].product_bundle,
- ],
- )
-
-_fuchsia_task_flash, _fuchsia_task_flash_for_test, fuchsia_task_flash = ffx_task_rule(
- doc = """Flash device using product bundle.""",
- implementation = _fuchsia_task_flash_impl,
- attrs = {
- "product_bundle": attr.label(
- doc = "Product bundle that is needed to flash the device",
- providers = [FuchsiaProductBundleInfo],
- mandatory = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_publish.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_publish.bzl
deleted file mode 100644
index fc5eedb..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_publish.bzl
+++ /dev/null
@@ -1,57 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Publishes packages as a workflow task."""
-
-load("@rules_fuchsia//fuchsia/private:providers.bzl", "FuchsiaPackageGroupInfo", "FuchsiaPackageInfo")
-load(":fuchsia_task.bzl", "fuchsia_task_rule")
-
-def _fuchsia_task_publish_impl(ctx, make_fuchsia_task):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- far_files = [
- pkg.far_file
- for dep in ctx.attr.packages
- for pkg in (dep[FuchsiaPackageGroupInfo].packages if FuchsiaPackageGroupInfo in dep else [dep[FuchsiaPackageInfo]])
- ]
-
- repo_name_args = [
- "--repo_name",
- ctx.attr.package_repository_name,
- ] if ctx.attr.package_repository_name else []
- return make_fuchsia_task(
- task_runner = ctx.attr._publish_packages_tool,
- prepend_args = [
- "--ffx",
- sdk.ffx,
- "--pm",
- sdk.pm,
- "--package",
- ] + far_files + repo_name_args,
- runfiles = [sdk.runfiles, far_files],
- )
-
-(
- _fuchsia_task_publish,
- _fuchsia_task_publish_for_test,
- fuchsia_task_publish,
-) = fuchsia_task_rule(
- implementation = _fuchsia_task_publish_impl,
- doc = """A workflow task that publishes multiple fuchsia packages.""",
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "packages": attr.label_list(
- doc = "The packages to publish.",
- providers = [[FuchsiaPackageInfo], [FuchsiaPackageGroupInfo]],
- ),
- "package_repository_name": attr.string(
- doc = "Optionally specify the repository name to publish these packages to.",
- ),
- "_publish_packages_tool": attr.label(
- doc = "The publish_packages tool.",
- default = "//fuchsia/tools:publish_packages",
- executable = True,
- cfg = "target",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_register_debug_symbols.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_register_debug_symbols.bzl
deleted file mode 100644
index 2bd66dd..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_register_debug_symbols.bzl
+++ /dev/null
@@ -1,49 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Registers debug symbols with ffx as a task workflow."""
-
-load("//fuchsia/private:fuchsia_debug_symbols.bzl", "collect_debug_symbols")
-load(":fuchsia_shell_task.bzl", "shell_task_rule")
-
-def _fuchsia_task_register_debug_symbols_impl(ctx, make_shell_task):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- build_id_dirs, build_dirs = zip(*[
- (build_id_dir, build_dir)
- for build_dir, build_id_dirs in collect_debug_symbols(ctx.attr.deps).build_id_dirs.items()
- for build_id_dir in build_id_dirs.to_list()
- ])
-
- return make_shell_task(
- command = [
- ctx.attr._tool,
- "--ffx",
- sdk.ffx,
- "--build-id-dirs",
- ] + list(build_id_dirs) + [
- "--build-dirs",
- ] + list(build_dirs),
- )
-
-(
- _fuchsia_task_register_debug_symbols,
- _fuchsia_task_register_debug_symbols_for_test,
- fuchsia_task_register_debug_symbols,
-) = shell_task_rule(
- doc = """Registers debug symbols with ffx.""",
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- implementation = _fuchsia_task_register_debug_symbols_impl,
- attrs = {
- "_tool": attr.label(
- doc = "The tool needed to register debug symbols.",
- default = "//fuchsia/tools:register_debug_symbols",
- ),
- "deps": attr.label_list(
- doc = """Collects FuchsiaDebugSymbolInfo across multiple dependencies.
- If a dependency does not provide the FuchsiaDebugSymbolInfo it will be ignored.
- """,
- mandatory = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_run_component.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_run_component.bzl
deleted file mode 100644
index b075d66..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_run_component.bzl
+++ /dev/null
@@ -1,90 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Runs components, tests components, or register drivers within a package."""
-
-load(":fuchsia_task.bzl", "fuchsia_task_rule")
-load(":providers.bzl", "FuchsiaComponentInfo", "FuchsiaPackageInfo")
-
-def _fuchsia_task_run_component_impl(ctx, make_fuchsia_task):
- sdk = ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"]
- repo = ctx.attr.repository
- package = ctx.attr.package[FuchsiaPackageInfo].package_name
- component = ctx.attr.component[FuchsiaComponentInfo]
- component_name = component.name
- manifest = component.manifest.basename
- url = "fuchsia-pkg://%s/%s#meta/%s" % (repo, package, manifest)
- moniker = ctx.attr.moniker or "/core/ffx-laboratory:%s" % component_name
- if component.is_driver:
- return make_fuchsia_task(
- ctx.attr._register_driver_tool,
- [
- "--ffx",
- sdk.ffx,
- "--url",
- url,
- ],
- )
- elif component.is_test:
- return make_fuchsia_task(
- ctx.attr._run_test_component_tool,
- [
- "--ffx",
- sdk.ffx,
- "--url",
- url,
- ],
- )
- else:
- return make_fuchsia_task(
- ctx.attr._run_component_tool,
- [
- "--ffx",
- sdk.ffx,
- "--moniker",
- moniker,
- "--url",
- url,
- ],
- )
-
-(
- _fuchsia_task_run_component,
- _fuchsia_task_run_component_for_test,
- fuchsia_task_run_component,
-) = fuchsia_task_rule(
- implementation = _fuchsia_task_run_component_impl,
- toolchains = ["@rules_fuchsia//fuchsia:toolchain"],
- attrs = {
- "repository": attr.string(
- doc = "The repository that has the published package.",
- mandatory = True,
- ),
- "package": attr.label(
- doc = "The package containing the component.",
- providers = [FuchsiaPackageInfo],
- mandatory = True,
- ),
- "moniker": attr.string(
- doc = "The moniker to run the component in. Only used for non-test non-driver components.",
- ),
- "component": attr.label(
- doc = "The component to run.",
- providers = [FuchsiaComponentInfo],
- mandatory = True,
- ),
- "_register_driver_tool": attr.label(
- doc = "The tool used to run components",
- default = "//fuchsia/tools:register_driver",
- ),
- "_run_test_component_tool": attr.label(
- doc = "The tool used to run components",
- default = "//fuchsia/tools:run_test_component",
- ),
- "_run_component_tool": attr.label(
- doc = "The tool used to run components",
- default = "//fuchsia/tools:run_component",
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_run_driver_tool.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_run_driver_tool.bzl
deleted file mode 100644
index 7495e2b..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_run_driver_tool.bzl
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Runs driver tools delivered within a package."""
-
-load(":fuchsia_task_ffx.bzl", "ffx_task_rule")
-load(":providers.bzl", "FuchsiaDriverToolInfo", "FuchsiaPackageInfo")
-
-def _fuchsia_task_run_driver_tool_impl(ctx, make_ffx_task):
- repo = ctx.attr.repository
- package = ctx.attr.package[FuchsiaPackageInfo].package_name
- tool_binary = ctx.attr.tool[FuchsiaDriverToolInfo].binary.dest
- url = "fuchsia-pkg://%s/%s#%s" % (repo, package, tool_binary)
- return make_ffx_task(prepend_args = [
- "driver",
- "run-tool",
- url,
- ])
-
-(
- _fuchsia_task_run_driver_tool,
- _fuchsia_task_run_driver_tool_for_test,
- fuchsia_task_run_driver_tool,
-) = ffx_task_rule(
- implementation = _fuchsia_task_run_driver_tool_impl,
- attrs = {
- "repository": attr.string(
- doc = "The repository that has the published package.",
- mandatory = True,
- ),
- "package": attr.label(
- doc = "The package containing the driver tool.",
- providers = [FuchsiaPackageInfo],
- mandatory = True,
- ),
- "tool": attr.label(
- doc = "The driver tool to run.",
- providers = [FuchsiaDriverToolInfo],
- mandatory = True,
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_verbs.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_verbs.bzl
deleted file mode 100644
index 602c6f4..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_task_verbs.bzl
+++ /dev/null
@@ -1,57 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-def _make_verb(verb = None):
- def _make(name):
- return name + "." + verb if verb else name
-
- return _make
-
-def make_help_executable(ctx, verbs, name = None):
- name = name or ctx.label.name
- exe = ctx.actions.declare_file(name + "_help_text.sh")
- tasks = ['echo " - {}: {}"'.format(verb(name), help) for (verb, help) in verbs.items()]
- ctx.actions.write(
- exe,
- """
- echo "------------------------------------------------------"{default_target_invalid_str}
- echo "USAGE: To interact with this object use the following tasks:"
- {tasks}
- echo "------------------------------------------------------"
- """.format(
- default_target_invalid_str = "" if _verbs.noverb in verbs else """
-echo "ERROR: The target '%s' cannot be run directly." """ % name,
- tasks = "\n".join(tasks),
- ),
- is_executable = True,
- )
- return exe
-
-def _make_verbs(*verbs):
- return struct(
- noverb = _make_verb(),
- custom = _make_verb,
- **{
- verb: _make_verb(verb)
- for verb in verbs
- }
- )
-
-_verbs = _make_verbs(*"""
-create
-debug_symbols
-delete
-delete_repo
-fetch
-help
-make_default
-publish
-reboot
-remove
-start
-stop
-wait
-""".strip().split("\n"))
-
-verbs = _verbs
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_workflow.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_workflow.bzl
deleted file mode 100644
index 8c0825f..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/fuchsia_workflow.bzl
+++ /dev/null
@@ -1,69 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Expresses an execution order for tasks."""
-
-load(":providers.bzl", "FuchsiaWorkflowEntityInfo", "FuchsiaWorkflowInfo")
-load(":workflow_entity.bzl", "workflow_entity_rule")
-
-def _collect_entities(initial, steps):
- # Basically merge N dictionaries.
- for step_entities in steps:
- for k, v in step_entities.items():
- if k in initial:
- # Sanity check.
- if (
- type(initial[k]) != type(v)
- ) or (
- initial[k].task_runner != v.task_runner if (
- hasattr(v, "task_runner")
- ) else initial[k].sequence != v.sequence
- ) or (
- initial[k].args != v.args
- ):
- fail("Invalid workflow state.")
- else:
- initial[k] = v
- return initial
-
-def fuchsia_workflow_rule(*, implementation, **kwargs):
- """Starlark higher-order rule for specifying a sequence of workflow entities."""
-
- def _fuchsia_workflow_impl(ctx, make_workflow_entity, collect_arguments):
- def _make_workflow(sequence, prepend_args = [], runfiles = []):
- workflow_args, runfiles = collect_arguments(prepend_args, runfiles)
- return make_workflow_entity(
- FuchsiaWorkflowInfo(
- entities = _collect_entities({
- ctx.label: FuchsiaWorkflowEntityInfo(
- sequence = [dep[FuchsiaWorkflowInfo].entrypoint for dep in sequence],
- args = workflow_args,
- ),
- }, [dep[FuchsiaWorkflowInfo].entities for dep in sequence]),
- entrypoint = ctx.label,
- ),
- sequence,
- runfiles,
- )
-
- return implementation(ctx, _make_workflow)
-
- return workflow_entity_rule(
- implementation = _fuchsia_workflow_impl,
- **kwargs
- )
-
-def _fuchsia_workflow_impl(ctx, make_workflow):
- return make_workflow(ctx.attr.sequence)
-
-_fuchsia_workflow, _fuchsia_workflow_for_test, fuchsia_workflow = fuchsia_workflow_rule(
- implementation = _fuchsia_workflow_impl,
- doc = """A grouping of tasks to be run sequentially.""",
- attrs = {
- "sequence": attr.label_list(
- doc = "The order of tasks to run.",
- providers = [FuchsiaWorkflowInfo],
- ),
- },
-)
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/providers.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/providers.bzl
deleted file mode 100644
index e058815..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/providers.bzl
+++ /dev/null
@@ -1,47 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""All Fuchsia Task Providers."""
-
-load(
- "@rules_fuchsia//fuchsia/private:providers.bzl",
- _FuchsiaComponentInfo = "FuchsiaComponentInfo",
- _FuchsiaDebugSymbolInfo = "FuchsiaDebugSymbolInfo",
- _FuchsiaDriverToolInfo = "FuchsiaDriverToolInfo",
- _FuchsiaPackageInfo = "FuchsiaPackageInfo",
- _FuchsiaProductBundleInfo = "FuchsiaProductBundleInfo",
- _FuchsiaProvidersInfo = "FuchsiaProvidersInfo",
-)
-
-FuchsiaTaskEntityInfo = provider(
- "The execution atomic within a workflow.",
- fields = {
- "task_runner": "The task's runner path.",
- "args": "A list of arguments to give the task runner.",
- "default_argument_scope": "The default scope of arguments to use for this task.",
- },
-)
-
-FuchsiaWorkflowEntityInfo = provider(
- "A sequence of tasks.",
- fields = {
- "sequence": "The sequence of tasks that need to be run.",
- "args": "A list of arguments to give tasks.",
- },
-)
-
-FuchsiaWorkflowInfo = provider(
- "All tasks + workflows that comprise the top-level workflow.",
- fields = {
- "entities": "A collection of tasks & workflows which comprise this workflow.",
- "entrypoint": "The entrypoint to this workflow.",
- },
-)
-
-FuchsiaComponentInfo = _FuchsiaComponentInfo
-FuchsiaDebugSymbolInfo = _FuchsiaDebugSymbolInfo
-FuchsiaDriverToolInfo = _FuchsiaDriverToolInfo
-FuchsiaPackageInfo = _FuchsiaPackageInfo
-FuchsiaProductBundleInfo = _FuchsiaProductBundleInfo
-FuchsiaProvidersInfo = _FuchsiaProvidersInfo
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/utils.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/utils.bzl
deleted file mode 100644
index 44d83d6..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/utils.bzl
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Common utilities used for workflows/tasks."""
-
-load("//fuchsia/private:fuchsia_transition.bzl", _with_fuchsia_transition = "with_fuchsia_transition")
-load(
- "//fuchsia/private:utils.bzl",
- _alias = "alias",
- _collect_runfiles = "collect_runfiles",
- _flatten = "flatten",
- _label_name = "label_name",
- _normalized_target_name = "normalized_target_name",
- _rule_variants = "rule_variants",
- _wrap_executable = "wrap_executable",
-)
-
-alias = _alias
-collect_runfiles = _collect_runfiles
-flatten = _flatten
-label_name = _label_name
-normalized_target_name = _normalized_target_name
-rule_variants = _rule_variants
-with_fuchsia_transition = _with_fuchsia_transition
-wrap_executable = _wrap_executable
-
-def full_product_bundle_url(ctx, pb_info):
- """ Returns the full url for the product bundle.
-
- If the product does not
- have a version associated with it the sdk version will be used. A valid
- fuchsia toolchain must be registered in the context.
- """
- version = pb_info.version or ctx.toolchains["@rules_fuchsia//fuchsia:toolchain"].sdk_id
- if not version:
- fail("Cannot find a version in the Fuchsia SDK")
-
- return "gs://fuchsia/development/{version}/sdk/product_bundles.json#{product}".format(
- version = version,
- product = pb_info.product_name,
- )
diff --git a/bazel_rules_fuchsia/fuchsia/private/workflows/workflow_entity.bzl b/bazel_rules_fuchsia/fuchsia/private/workflows/workflow_entity.bzl
deleted file mode 100644
index 0f654a5..0000000
--- a/bazel_rules_fuchsia/fuchsia/private/workflows/workflow_entity.bzl
+++ /dev/null
@@ -1,149 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Helper rules for creating workflow entities."""
-
-load(
- ":utils.bzl",
- "alias",
- "collect_runfiles",
- "rule_variants",
- "with_fuchsia_transition",
- "wrap_executable",
-)
-
-def workflow_entity_rule(*, implementation, attrs = {}, **kwargs):
- def workflow_entity_impl(ctx):
- if ctx.attr.args:
- fail("Please use the `arguments` attribute instead of `args`.")
-
- def _make_workflow(workflow, *runfiles):
- """Generates a workflow runner invocation given a FuchsiaWorkflowInfo and returns all providers.
-
- Args:
- workflow: The workflow to provide the workflow runner.
- *runfiles: Additional runfiles dependencies for this workflow entity.
-
- Returns:
- A DefaultInfo invocation of the corresponding workflow and the FuchsiaWorkflowInfo.
- """
- manifest = ctx.actions.declare_file("%s_workflow.json" % ctx.attr.name.removesuffix("_base"))
- ctx.actions.write(manifest, json.encode_indent({
- "entities": {
- str(label).removesuffix("_base"): {
- "type": "task",
- "task_runner": entity.task_runner,
- "args": entity.args,
- "default_argument_scope": entity.default_argument_scope,
- } if hasattr(entity, "task_runner") else {
- "type": "workflow",
- "sequence": [str(step).removesuffix("_base") for step in entity.sequence],
- "args": entity.args,
- }
- for label, entity in workflow.entities.items()
- },
- "entrypoint": str(workflow.entrypoint).removesuffix("_base"),
- }))
-
- invocation, runner_runfiles = wrap_executable(
- ctx,
- ctx.attr._unbuffer_tool,
- ctx.attr._run_workflow,
- "--workflow-manifest",
- manifest,
- script_name = "%s.sh" % ctx.attr.name.removesuffix("_base"),
- )
- return [
- workflow,
- DefaultInfo(
- executable = invocation,
- files = depset([invocation, manifest]),
- runfiles = collect_runfiles(
- ctx,
- runner_runfiles,
- ctx.attr.inputs,
- *runfiles
- ),
- ),
- ]
-
- def _collect_arguments(prepend_task_args = [], *runfiles):
- """Interpolates task arguments and collects runfiles."""
- arguments = prepend_task_args + ctx.attr.arguments
- task_runfiles = collect_runfiles(ctx, ctx.attr.inputs, runfiles, arguments, ignore_types = ["string"])
-
- # TODO(fxbug.dev/114470): Interpolate input file locations.
- return [
- arg.short_path if type(arg) == "File" else arg
- for arg in arguments
- ], task_runfiles
-
- return implementation(ctx, _make_workflow, _collect_arguments)
-
- rules = rule_variants(
- implementation = workflow_entity_impl,
- variants = ("executable", "test"),
- attrs = dict(attrs, **{
- "_unbuffer_tool": attr.label(
- default = "//fuchsia/tools:unbuffer",
- doc = "Pass-through executable that unbuffers command stdout/stderr.",
- executable = True,
- cfg = "target",
- ),
- "_run_workflow": attr.label(
- default = "//fuchsia/tools:run_workflow",
- doc = "The workflow runner tool.",
- executable = True,
- cfg = "target",
- ),
- "arguments": attr.string_list(
- doc = "Specify arguments for this workflow entity.",
- ),
- "default_argument_scope": attr.string(
- doc = "The scope of arguments to use for the workflow entity.",
- default = "explicit",
- values = ["explicit", "workflow", "global"],
- ),
- "inputs": attr.label_list(
- doc = "Task dependencies. Use `$location(path/to/file)` to reference these in arguments.",
- ),
- }),
- **kwargs
- )
-
- def macro(
- *,
- name,
- apply_fuchsia_transition = False,
- testonly = False,
- tags = None,
- visibility = None,
- **kwargs):
- # Switch between the test and non-test workflow variant based on testonly.
- rules[1 if testonly else 0](
- name = name + "_base",
- tags = tags,
- visibility = visibility,
- **kwargs
- )
-
- (with_fuchsia_transition if apply_fuchsia_transition else alias)(
- name = name,
- actual = name + "_base",
- executable = True,
- testonly = testonly,
- tags = tags,
- visibility = visibility,
- )
-
- # Because cc_test needs all transitive dependent ancestors to be test rules
- # (testonly is not sufficient), we return 3 values to be unpacked:
- # 1. The non-test workflow entity rule variant,
- # 2. The test workflow entity rule variant, and
- # 3. A wrapper macro that invokes either `1` or `2` based on `testonly`.
- # The wrapper macro can also optionally apply a fuchsia_transition.
- #
- # We can't omit `1` or `2`, since bazel needs each rule to be assigned a
- # name and exportable by a `.bzl` file.
- return rules + [macro]
diff --git a/bazel_rules_fuchsia/fuchsia/tools/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/tools/BUILD.bazel
deleted file mode 100644
index ef52eda..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/BUILD.bazel
+++ /dev/null
@@ -1,132 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Tools supporting Fuchsia Bazel rules.
-
-load("@rules_python//python:defs.bzl", "py_binary")
-
-package(default_visibility = ["//visibility:public"])
-
-py_binary(
- name = "unbuffer",
- srcs = ["unbuffer.py"],
- python_version = "PY3",
-)
-
-sh_binary(
- name = "elf_strip",
- srcs = ["elf_strip.sh"],
-)
-
-sh_binary(
- name = "generate_symbols_dir",
- srcs = ["generate_symbols_dir.sh"],
-)
-
-py_binary(
- name = "publish_packages",
- srcs = ["publish_packages.py"],
- python_version = "PY3",
-)
-
-py_binary(
- name = "rebase_product_config",
- srcs = ["rebase_product_config.py"],
- python_version = "PY3",
-)
-
-py_binary(
- name = "add_parameters",
- srcs = ["add_parameters.py"],
- python_version = "PY3",
-)
-
-py_binary(
- name = "rebase_package_manifest",
- srcs = ["rebase_package_manifest.py"],
- python_version = "PY3",
-)
-
-py_binary(
- name = "add_base_pkgs",
- srcs = ["add_base_pkgs.py"],
- python_version = "PY3",
-)
-
-py_library(
- name = "fuchsia_task_lib",
- srcs = ["fuchsia_task_lib.py"],
-)
-
-py_binary(
- name = "run_workflow",
- srcs = ["run_workflow.py"],
- python_version = "PY3",
- deps = [":fuchsia_task_lib"],
-)
-
-py_binary(
- name = "fuchsia_shell_task",
- srcs = ["fuchsia_shell_task.py"],
- python_version = "PY3",
- deps = [":fuchsia_task_lib"],
-)
-
-py_binary(
- name = "register_debug_symbols",
- srcs = ["register_debug_symbols.py"],
- python_version = "PY3",
- deps = [":fuchsia_task_lib"],
-)
-
-py_binary(
- name = "register_driver",
- srcs = ["register_driver.py"],
- python_version = "PY3",
- deps = [":fuchsia_task_lib"],
-)
-
-py_binary(
- name = "run_test_component",
- srcs = ["run_test_component.py"],
- python_version = "PY3",
- deps = [":fuchsia_task_lib"],
-)
-
-py_binary(
- name = "run_component",
- srcs = ["run_component.py"],
- python_version = "PY3",
-)
-
-py_binary(
- name = "clean_repo",
- srcs = ["clean_repo.py"],
- python_version = "PY3",
- deps = [
- ":fuchsia_task_lib",
- ],
-)
-
-py_binary(
- name = "development_status",
- srcs = ["development_status.py"],
- python_version = "PY3",
- deps = [
- ":fuchsia_task_lib",
- ],
-)
-
-py_binary(
- name = "detect_target",
- srcs = ["detect_target.py"],
- python_version = "PY3",
- deps = [":fuchsia_task_lib"],
-)
-
-py_binary(
- name = "json_comparator",
- srcs = ["json_comparator.py"],
- python_version = "PY3",
-)
diff --git a/bazel_rules_fuchsia/fuchsia/tools/add_base_pkgs.py b/bazel_rules_fuchsia/fuchsia/tools/add_base_pkgs.py
deleted file mode 100755
index 98853dc..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/add_base_pkgs.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-"""Rebase paths in product config to be relative to artifact_base_path."""
-
-import argparse
-import json
-import os
-
-
-def parse_args():
- """Parses command-line arguments."""
- parser = argparse.ArgumentParser()
- parser.add_argument(
- '--product-config',
- type=argparse.FileType('r'),
- help='original product config file',
- required=True,
- )
- parser.add_argument(
- '--updated-product-config',
- type=argparse.FileType('w'),
- help='output product config file',
- required=True,
- )
- parser.add_argument(
- '--base-details',
- help='Details of additional base packages',
- required=True,
- )
- parser.add_argument(
- '--relative-base',
- help='Path to artifact base',
- required=True,
- )
- return parser.parse_args()
-
-
-def main():
- args = parse_args()
- base_path = args.relative_base
- product_config_json = json.load(args.product_config)
- additional_base_pkgs = json.loads(args.base_details)
- if not additional_base_pkgs:
- json.dump(product_config_json, args.updated_product_config, indent=2)
- return
-
- for package in additional_base_pkgs:
- package['manifest'] = os.path.relpath(package['manifest'], base_path)
- if 'config_data' not in package:
- continue
- for config_data in package['config_data']:
- config_data['source'] = os.path.relpath(config_data['source'],
- base_path)
- if 'base' not in product_config_json['product']['packages']:
- product_config_json['product']['packages']['base'] = []
- product_config_json['product']['packages']['base'].extend(
- additional_base_pkgs)
-
- json.dump(product_config_json, args.updated_product_config, indent=2)
-
-
-if __name__ == '__main__':
- main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/add_parameters.py b/bazel_rules_fuchsia/fuchsia/tools/add_parameters.py
deleted file mode 100755
index 79ca71d..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/add_parameters.py
+++ /dev/null
@@ -1,78 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-"""Rebase paths in product config to be relative to artifact_base_path."""
-
-import argparse
-import json
-from typing import Dict, Any
-
-
-def parse_args():
- """Parses command-line arguments."""
- parser = argparse.ArgumentParser()
- parser.add_argument(
- '--product-config-path',
- help='Path to product config',
- required=True,
- )
- parser.add_argument(
- '--additional-bool',
- help='Additional bool flags',
- )
- parser.add_argument(
- '--additional-string',
- help='Additional string flags',
- )
- parser.add_argument(
- '--additional-int',
- help='Additional int flags',
- )
- parser.add_argument(
- '--output',
- help='Path to output product config',
- required=True,
- )
- return parser.parse_args()
-
-
-def add_new_parameter(config: Dict[str, Any], key: str, value: str,
- value_type: str):
- if '.' not in key:
- if value_type == 'bool':
- config[key] = value == 'true'
- if value_type == 'str':
- config[key] = value
- if value_type == 'int':
- config[key] = int(value)
- return config
-
- path_seg = key.split('.', 1)
- sub_config = config[path_seg[0]] if path_seg[0] in config else {}
- config[path_seg[0]] = add_new_parameter(sub_config, path_seg[1], value, value_type)
- return config
-
-
-def main():
- args = parse_args()
- with open(args.product_config_path, 'r') as f:
- product_config_json = json.load(f)
-
- platform_config = product_config_json['platform']
-
- dict_bool = json.loads(args.additional_bool)
- for key in dict_bool:
- add_new_parameter(platform_config, key, dict_bool[key], 'bool')
- dict_int = json.loads(args.additional_int)
- for key in dict_int:
- add_new_parameter(platform_config, key, dict_int[key], 'int')
- dict_string = json.loads(args.additional_string)
- for key in dict_string:
- add_new_parameter(platform_config, key, dict_string[key], 'str')
-
- with open(args.output, 'w') as f:
- json.dump(product_config_json, f, indent=2)
-
-
-if __name__ == '__main__':
- main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/clean_repo.py b/bazel_rules_fuchsia/fuchsia/tools/clean_repo.py
deleted file mode 100644
index 6eeeccb..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/clean_repo.py
+++ /dev/null
@@ -1,136 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import argparse
-import json
-import subprocess
-import os
-
-from pathlib import Path
-from shutil import rmtree
-from fuchsia_task_lib import Terminal
-
-def run(*command):
- try:
- return subprocess.check_output(
- command,
- text=True,
- ).strip()
- except subprocess.CalledProcessError as e:
- print(e.stdout)
- raise e
-
-def parse_args():
- '''Parses arguments.'''
- parser = argparse.ArgumentParser()
-
- def path_arg(type='file'):
- def arg(path):
- path = Path(path)
- if path.is_file() != (type == 'file') or path.is_dir() != (type == 'directory'):
- parser.error(f'Path "{path}" is not a {type}!')
- return path
- return arg
-
-
- parser.add_argument(
- '--ffx',
- type=path_arg(),
- help='A path to the ffx tool.',
- required=True,
- )
- parser.add_argument(
- '--name',
- type=str,
- help='The name of the repository to clean',
- required=True,
- )
- parser.add_argument(
- '--fallback_path',
- type=str,
- help='The path that the user thinks should hold the package.',
- required=False,
- )
-
- parser.add_argument(
- '--delete_contents',
- help='If True, the on-disk contents will be deleted',
- action='store_true'
- )
- parser.add_argument(
- '--no-delete_contents',
- help='If True, the on-disk contents will be deleted',
- dest='delete_contents',
- action='store_false'
- )
- parser.set_defaults(delete_contents=True)
-
- return parser.parse_args()
-
-def repo_path(args):
- '''Checks if the repo exists and returns the path'''
- repos = json.loads(run(
- args.ffx,
- '--machine',
- 'JSON', 'repository',
- 'list'
- ))
- for repo in repos:
- if repo['name'] == args.name:
- return repo['spec']['path']
-
- return None
-
-def rm_repo(args, path):
- '''Removes the repo from ffx and on disk'''
- run(args.ffx, 'repository', 'remove', args.name)
- try:
- if args.delete_contents:
- rmtree(path)
- except:
- print("Unable to remove package repository '{}' at {}".format(args.name, path))
- print("This package was likely removed by another process and not removed from ffx.")
-
- return None
-
-
-def prompt_for_deleting_repo(args):
- print(f'{Terminal.red("WARNING:")} package repository {args.name} is not registered with ffx.')
- print('This likely means it was removed by another process and will need to be manually removed.')
- if not args.fallback_path:
- return
-
- if os.path.isabs(args.fallback_path):
- path = args.fallback_path
- else:
- path = os.path.join(os.environ['BUILD_WORKSPACE_DIRECTORY'], args.fallback_path)
-
- # Check if the path looks like a package repo
- try:
- contents = os.listdir(path)
- expected_contents = ['staged', 'repository', 'keys']
- looks_like_repo = all(items in contents for items in expected_contents)
- except:
- looks_like_repo = False
-
- if looks_like_repo:
- print(f'Attempting to delete {Terminal.underline(path)}')
- should_delete = input('Would you like to proceed? (y/n): ').lower()
- if should_delete == 'y':
- rmtree(path)
-
-
-def main():
- # Parse arguments.
- args = parse_args()
- path = repo_path(args)
- if path:
- rm_repo(args, path)
- else:
- prompt_for_deleting_repo(args)
-
-
-if __name__ == '__main__':
- main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/cp.sh b/bazel_rules_fuchsia/fuchsia/tools/cp.sh
deleted file mode 100755
index db78e63..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/cp.sh
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/bin/bash
-
-# A cp wrapper that only adds `-R` if SRC is a dir, so it works on MacOS.
-#
-# Usage: ./cp.sh SRC DEST [OPTIONS...]
-
-set -euo pipefail
-
-if [[ -d $1 ]]; then
- cp -R $@
-else
- cp $@
-fi
diff --git a/bazel_rules_fuchsia/fuchsia/tools/detect_target.py b/bazel_rules_fuchsia/fuchsia/tools/detect_target.py
deleted file mode 100644
index 33427fb..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/detect_target.py
+++ /dev/null
@@ -1,177 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import argparse
-import json
-import subprocess
-import sys
-
-from pathlib import Path
-from fuchsia_task_lib import Terminal
-
-_PRODUCT_BUNDLE_REPO_ALIASES = ['fuchsia.com', 'chromium.org']
-
-def run_json(*command):
- return json.loads(run(*command))
-
-
-def run(*command):
- try:
- return subprocess.check_output(
- command,
- text=True,
- ).strip()
- except subprocess.CalledProcessError as e:
- print(e.stdout)
- raise e
-
-
-class Target:
- def __init__(self, json):
- def child_value(e, name):
- for c in entry['child']:
- if c['label'] == name:
- return c['value']
- return None
-
- for entry in json:
- label = entry['label']
- if label == 'target':
- self.name = child_value(entry, 'name')
- elif label == 'build':
- self.product = child_value(entry, 'product')
- self.board = child_value(entry, 'board')
- self.version = child_value(entry, 'version')
-
-
-def parse_args():
- '''Parses arguments.'''
- parser = argparse.ArgumentParser()
-
- def path_arg(type='file'):
- def arg(path):
- path = Path(path)
- if path.is_file() != (type == 'file') or path.is_dir() != (type == 'directory'):
- parser.error(f'Path "{path}" is not a {type}!')
- return path
- return arg
-
- parser.add_argument(
- '--ffx',
- type=path_arg(),
- help='A path to the ffx tool.',
- required=True,
- )
-
- parser.add_argument(
- '--product_bundle',
- type=str,
- help='The name of the product bunde (<product>.<board>).',
- required=True,
- )
-
- parser.add_argument(
- '--product_bundle_repo',
- type=str,
- help='The name of the product bunde repository hosting the product bundle.',
- required=True,
- )
-
- parser.add_argument(
- '--package_repo',
- type=str,
- help='The name of the package repo to register with the target.',
- required=False,
- )
-
- return parser.parse_args()
-
-
-def all_targets(args):
- try:
- target_list_result = run_json(args.ffx, '--machine', 'json', 'target', 'list')
- except:
- return []
-
- nodes = [t['nodename'] for t in target_list_result]
- targets = []
- for node in nodes:
- node_json = run_json(args.ffx, '--target', node, 'target', 'show', '--json')
- targets.append(Target(node_json))
-
- return targets
-
-
-def get_product_and_board(args):
- return args.product_bundle.split(".")
-
-def filter_targets(args, targets):
- (product, board) = get_product_and_board(args)
- filtered = []
- for target in targets:
- if target.product == product and target.board == board:
- filtered.append(target)
-
- return filtered
-
-
-def make_target_default(args, target):
- green_name = Terminal.green(target.name)
- print('Setting {} as default target'.format(green_name))
- run(args.ffx, 'target', 'default', 'set', target.name)
-
-
-def register_repo_with_target(args, target, repo, aliases = []):
- cmd = [args.ffx,
- "target",
- "repository",
- "register",
- "-r",
- repo,
- ]
- for alias in aliases:
- cmd.extend(["--alias", alias])
-
- run(*cmd)
-
-
-def detect_target(args, targets):
- assert(len(targets) > 0)
-
- if len(targets) > 1:
- # TODO: Make it so users can select their target here
- print(f'{Terminal.red("FAIL")} - multiple targets found cannot set default"')
- else:
- target = targets[0]
- if args.product_bundle_repo:
- register_repo_with_target(args, target, args.product_bundle_repo, _PRODUCT_BUNDLE_REPO_ALIASES)
- if args.package_repo:
- register_repo_with_target(args, target, args.package_repo)
-
- make_target_default(args, target)
-
-
-def notify_no_targets_found(args, known_targets):
- print(f'{Terminal.red("ERROR: No targets found running {}".format(args.product_bundle))}')
- if known_targets:
- print('The following targets were found:')
- for target in known_targets:
- print(' - {} ({}.{})'.format(target.name, target.product, target.board))
- sys.exit(1)
-
-
-def main():
- args = parse_args()
- known_targets = all_targets(args)
- matching_targets = filter_targets(args, known_targets)
-
- if matching_targets:
- detect_target(args, matching_targets)
- else:
- notify_no_targets_found(args, known_targets)
-
-
-if __name__ == "__main__":
- main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/development_status.py b/bazel_rules_fuchsia/fuchsia/tools/development_status.py
deleted file mode 100644
index 011b5a2..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/development_status.py
+++ /dev/null
@@ -1,348 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import argparse
-import datetime
-import json
-import subprocess
-
-from pathlib import Path
-from fuchsia_task_lib import Terminal
-
-
-def run(*command):
- try:
- return subprocess.check_output(
- command,
- text=True,
- ).strip()
- except subprocess.CalledProcessError as e:
- print(e.stdout)
- raise e
-
-
-def run_checked(*command):
- try:
- subprocess.run(
- command,
- stderr=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL,
- ).check_returncode()
- return True
- except subprocess.CalledProcessError as e:
- return False
-
-
-def print_title(msg):
- print(f'\n{Terminal.bold("-- {} --".format(msg))}\n')
-
-
-def parse_args():
- '''Parses arguments.'''
- parser = argparse.ArgumentParser()
-
- def path_arg(type='file'):
- def arg(path):
- path = Path(path)
- if path.is_file() != (type == 'file') or path.is_dir() != (type == 'directory'):
- parser.error(f'Path "{path}" is not a {type}!')
- return path
- return arg
-
- parser.add_argument(
- '--ffx',
- type=path_arg(),
- help='A path to the ffx tool.',
- required=True,
- )
-
- parser.add_argument(
- '--name',
- type=str,
- help='The name of the configuration.',
- required=True,
- )
-
- parser.add_argument(
- "--expected_emulator",
- type=str,
- help='The expected name of the running emulator',
- required=False,
- )
-
- parser.add_argument(
- "--expected_package_repo",
- type=str,
- help='The expected package repository',
- required=False,
- )
-
- parser.add_argument(
- "--expected_product_bundle",
- type=str,
- help='The expected product bundle url',
- required=False,
- )
-
- parser.add_argument(
- "--expected_product_bundle_repo",
- type=str,
- help='The expected product bundle repo name',
- required=False,
- )
-
- parser.add_argument(
- "--expected_sdk_version",
- type=str,
- help='The expected sdk version',
- required=False,
- )
-
- parser.add_argument(
- "--expected_product_name",
- type=str,
- help='The expected product name',
- required=False,
- )
-
- return parser.parse_args()
-
-
-class Emulator:
- def __init__(self, active, name):
- self.active = active
- self.name = name
-
-
-class BuildInfo:
- def __init__(self, sdk_version, product_config):
- self.sdk_version = sdk_version
- self.product_config = product_config
-
-
-def all_emulators(args):
- raw_emulators = run(args.ffx, "emu", "list")
- if not raw_emulators:
- return []
-
- emulators = []
- for emulator in raw_emulators.split('\n'):
- emulator_entries = [v for v in emulator.split(' ') if v]
- (active, name) = (emulator_entries[0], emulator_entries[1])
- emulators.append(Emulator(active == '[Active]', name))
- return emulators
-
-
-def all_package_repo_names(args):
- repos = json.loads(run(args.ffx, "--machine", "JSON", "repository", "list"))
- return [repo["name"] for repo in repos]
-
-
-def target_reachable(args, target):
- return run_checked(args.ffx, '--target', target, "target", 'wait', '-t', "5")
-
-
-def get_current_default_target(args):
- return run(args.ffx, "target", "default", "get")
-
-
-def is_repo_registered_with_target(args, repo, target):
- # target repository list does not support JSON output so we have to parse the output.
- # this is fragile so migrate once json is supported.
- output = run(args.ffx, "target", "repository", "list")
- output_rows = output.split("\n")
- for i, row in enumerate(output_rows):
- if row.find(repo) > 0:
- for j in range(i, len(output_rows)):
- if output_rows[j].startswith("+"):
- break
- if output_rows[j].find(target) > 0:
- return True
- return False
-
-
-def build_info_for_target(args, target):
- if not target_reachable(args, target):
- return ""
-
- result = json.loads(run(args.ffx, '--target', target, 'target', 'show', '--json'))
- sdk_version = ""
- product_config = ""
- for entry in result:
- if entry['label'] == 'build':
- for child in entry['child']:
- label = child['label']
- if label == 'version':
- sdk_version = child['value']
- elif label == 'product':
- product_config = child['value']
-
- return BuildInfo(sdk_version=sdk_version, product_config=product_config)
-
-
-def is_product_bundle_downloaded(args):
- # product-bundle list does not support JSON output so we have to parse the output.
- # this is fragile so migrate once json is supported.
- output = run(args.ffx, 'product-bundle', 'list')
- pb_url = args.expected_product_bundle
- for line in output.split('\n'):
- if line.find(pb_url) >= 0 and line.startswith('*'):
- return True
- return False
-
-
-
-def show_header(args):
- sdk_version = run(args.ffx, 'sdk', 'version')
- print('')
- print(f'{Terminal.bold("Status of development environment: {}".format(args.name))}')
- print(f' - Current SDK Version: {sdk_version}')
-
-
-def show_target_summary(args, current_default_target, print_pass, print_fail):
- print_title('Checking Target Status')
- if current_default_target:
- print_pass(f'default target set to "{current_default_target}"')
- else:
- print_fail('no default target specified')
-
- print(f'\n{Terminal.bold("Known Targets:")}')
- try:
- targets = json.loads(run(args.ffx, "--machine", "json", "target", "list"))
- except:
- targets = []
-
- if len(targets) > 0:
- [print(f'- {t["nodename"]} ({t["target_type"]})') for t in targets]
- else:
- print_fail('no known targets')
-
- if args.expected_emulator:
- show_emulator_status(args, args.expected_emulator, current_default_target, print_pass, print_fail)
-
- if current_default_target != args.expected_emulator:
- show_reachability_of_target(args, current_default_target, print_pass, print_fail)
-
-
-def show_emulator_status(args, emulator, default_target, print_pass, print_fail):
- print_title('Checking status of emulator "{}"'.format(emulator))
- if emulator == default_target:
- print_pass(f'expected emulator "{emulator}" is the default target')
- else:
- print_fail(f'expected "{emulator}" to be the default target but it is not')
-
- show_reachability_of_target(args, emulator, print_pass, print_fail)
-
-
-def show_reachability_of_target(args, target, print_pass, print_fail):
- is_reachable = target_reachable(args, target)
- if is_reachable:
- print_pass(f'{target} is running and reachable')
- show_build_info_status(args, target, print_pass, print_fail)
- else:
- print_fail(f'{target} is not running')
-
-def show_build_info_status(args, target, print_pass, print_fail):
- build_info = build_info_for_target(args, target)
- if args.expected_sdk_version:
- try:
- build_date = datetime.datetime.fromisoformat(build_info.sdk_version)
- print(f'Cannot determine SDK version for "{target}"')
- print(f'{target} is running a build from {build_info.sdk_version}')
- except:
- if build_info.sdk_version == args.expected_sdk_version:
- print_pass(f'{target} is running the expected sdk version of "{args.expected_sdk_version}"')
- else:
- print_fail(f'{target} is running sdk version "{build_info.sdk_version}" which does not match the expected "{args.expected_sdk_version}"')
-
- if args.expected_product_name:
- expected_product_config = args.expected_product_name.split(".")[0]
- if build_info.product_config == expected_product_config:
- print_pass(f'{target} is running the expected product "{expected_product_config}"')
- else:
- print_fail(f'{target} is running product "{build_info.product_config}" which does not match the expected "{expected_product_config}"')
-
-
-def show_package_repo_status(args, default_target, print_pass, print_fail):
- print_title('Checking status of package repositories')
- print(f'{Terminal.bold("Known Package Repositories:")}')
-
- # FIX IF NOT HERE
-
- repos = all_package_repo_names(args)
- if repos:
- [print(f' - {r}') for r in repos]
- else:
- print_fail('No active repositories')
-
- current_default_repo = run(args.ffx, "repository", "default", "get")
- if args.expected_package_repo:
- print('')
- if current_default_repo == args.expected_package_repo:
- print_pass(f'package repository "{current_default_repo}" is the default repository')
- else:
- print_fail(f'expected repository "{args.expected_package_repo}" to be the default repository but it is not')
-
- show_status_of_repository_registration(args, args.expected_package_repo, default_target, print_pass, print_fail)
-
-
-def show_status_of_repository_registration(args, repo, default_target, print_pass, print_fail):
- if is_repo_registered_with_target(args, repo, default_target):
- print_pass(f'package repository "{repo}" is registered with the default target')
- else:
- print_fail(f'package repository "{repo}" is not registered with the default target')
-
- if args.expected_emulator:
- if is_repo_registered_with_target(args, repo, args.expected_emulator):
- print_pass(f'package repository "{repo}" is registered with emulator "{args.expected_emulator}"')
- else:
- print_fail(f'package repository "{repo}" is not registered with emulator "{args.expected_emulator}"')
-
-
-def show_product_bundle_status(args, default_target, print_pass, print_fail):
- if not args.expected_product_bundle:
- return
-
- print_title("Checking status of product bundle")
- if is_product_bundle_downloaded(args):
- print_pass(f'{args.expected_product_bundle} is downloaded.')
- else:
- print_fail(f'{args.expected_product_bundle} is not downloaded.')
-
- if args.expected_product_bundle_repo:
- repos = all_package_repo_names(args)
- if args.expected_product_bundle_repo in repos:
- print_pass(f'package repository hosting the product bundle packages "{args.expected_product_bundle_repo}" exists.')
- else:
- print_fail(f'product bundle does not have a package repository "{args.expected_product_bundle_repo}"')
-
- show_status_of_repository_registration(args, args.expected_product_bundle_repo, default_target, print_pass, print_fail)
-
-
-def main():
- args = parse_args()
- default_target = get_current_default_target(args)
- failures = []
-
- def print_pass(msg):
- print(f' {Terminal.green("PASS")} - {msg}')
-
- def print_fail(msg):
- failures.append(msg)
- print(f' {Terminal.red("FAIL")} - {msg}')
-
- show_header(args)
- show_target_summary(args, default_target, print_pass, print_fail)
- show_package_repo_status(args, default_target, print_pass, print_fail)
- show_product_bundle_status(args, default_target, print_pass, print_fail)
-
- if len(failures) > 0:
- print('')
- print(f'{Terminal.bold("Some checks failed. To fix these problems run:")}')
- print(" bazel run {}".format(args.name))
-
-
-if __name__ == '__main__':
- main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/elf_strip.sh b/bazel_rules_fuchsia/fuchsia/tools/elf_strip.sh
deleted file mode 100755
index c096da0..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/elf_strip.sh
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/bin/bash
-
-# Strips the binary and produces a single-line ids.txt file
-#
-# The output file will be a single-line ids.txt file in the format of
-# "<elf_with_symbols_file> <debug_file>".
-#
-# If the source file is not an ELF file or does not contain a build ID, the
-# output file will be empty.
-#
-# This script should only be invoked by fuchsia_package_impl in
-# fuchsia_package.bzl.
-
-# Exits on any failure
-set -euf -o pipefail
-
-if [[ $# != 4 ]]; then
- echo >&2 "Error: invalid invocation of $0: $@"
- exit 1
-fi
-
-readonly _objcopy="$1"
-readonly elf_with_symbols_file="$2"
-readonly elf_stripped="$3"
-readonly ids_txt="$4"
-
-readonly info="$(file -L "${elf_with_symbols_file}")"
-
-# If this file is not an ELF, e.g. a font file or an image,
-# or if this file has no symbols to strip, then we just copy this file
-# as-is.
-if [[ ! "$info" =~ " ELF " || "$info" =~ "no section header" ]]; then
- cp "${elf_with_symbols_file}" "${elf_stripped}"
- # Create an empty ids.txt.
- touch "${ids_txt}"
- exit
-fi
-
-# strip symbols from the ELF
-"${_objcopy}" --strip-all "${elf_with_symbols_file}" "${elf_stripped}"
-
-# Get build ID.
-if ! [[ "$info" =~ (BuildID\[[^\]]*\]=)([^, ]*) ]]; then
- echo >&2 "WARNING: No build id in ELF: ${elf_with_symbols_file}"
- touch "${ids_txt}"
- exit
-fi
-
-readonly build_id="${BASH_REMATCH[2]}"
-echo "${build_id}" "${elf_with_symbols_file}" > "${ids_txt}"
diff --git a/bazel_rules_fuchsia/fuchsia/tools/fuchsia_shell_task.py b/bazel_rules_fuchsia/fuchsia/tools/fuchsia_shell_task.py
deleted file mode 100644
index 673fc1a..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/fuchsia_shell_task.py
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import os
-import subprocess
-
-from shutil import which
-
-from fuchsia_task_lib import *
-
-class FuchsiaShellTask(FuchsiaTask):
- def try_resolve(self, executable: str) -> str:
- result = Path(which(executable) or '').resolve()
- return str(result) if result.is_file() and os.access(result, os.X_OK) else executable
-
- def run(self, parser: ScopedArgumentParser) -> None:
- executable, *arguments = parser.get_default_arguments()
- command = [self.try_resolve(executable), *arguments]
- try:
- subprocess.check_call(' '.join(command), shell=True)
- except subprocess.SubprocessError:
- raise TaskExecutionException(f'Shell task {command} failed.')
-
-if __name__ == '__main__':
- FuchsiaShellTask.main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/fuchsia_task_lib.py b/bazel_rules_fuchsia/fuchsia/tools/fuchsia_task_lib.py
deleted file mode 100644
index 9854809..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/fuchsia_task_lib.py
+++ /dev/null
@@ -1,268 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import argparse
-import json
-import os
-import sys
-
-from abc import abstractmethod
-from contextlib import contextmanager
-from enum import Enum
-from functools import cached_property, total_ordering, reduce
-from pathlib import Path
-from typing import Any, Dict, List, Optional
-
-
-class TaskExecutionException(Exception):
- def __init__(self, *args: object, is_caught_failure: bool = False) -> None:
- super().__init__(*args)
- self._is_caught_failure = is_caught_failure
-
- @property
- def is_caught_failure(self) -> bool:
- return self._is_caught_failure
-
-
-class Terminal:
- def if_no_color(text: str, if_colored: str = '') -> str:
- return if_colored if Terminal.supports_color() else text
-
- def bold(text: str) -> str:
- return Terminal._style(text, 1)
-
- def underline(text: str) -> str:
- return Terminal._style(text, 4)
-
- def red(text: str) -> str:
- return Terminal._style(text, 91)
-
- def green(text: str) -> str:
- return Terminal._style(text, 92)
-
- def purple(text: str) -> str:
- return Terminal._style(text, 95)
-
- def cyan(text: str) -> str:
- return Terminal._style(text, 96)
-
- def supports_color() -> bool:
- return sys.stdout.isatty() and sys.stderr.isatty() and not os.environ.get('NO_COLOR')
-
- def _style(text: str, escape_code: int) -> str:
- if Terminal.supports_color():
- return f'\033[{escape_code}m{text}\033[0m'
- else:
- # If neither stdout nor stderr is not a tty then any styles likely
- # won't get rendered correctly when the text is eventually printed,
- # so don't apply the style.
- return text
-
-@total_ordering
-class ArgumentScope(Enum):
- # Captures arguments that are passed directly to the current task:
- # 1. via command line: `bazel run :workflow -- 'TASK_MNEMONIC=--foo --bar'`
- # 2. via build rule: `arguments = ["--foo", "--bar"]`
- EXPLICIT = ()
- # Captures arguments that are passed to any parent workflow:
- # 1. via command line: `bazel run :workflow -- 'WORKFLOW_MNEMONIC=--foo --bar'`
- # 2. via build rule: `arguments = ["--foo", "--bar"]`
- # 3. Includes any EXPLICIT arguments.
- WORKFLOW = (*EXPLICIT, '__WORKFLOW_ARGUMENT__')
- # Captures any top level arguments:
- # 1. via command line: `bazel run :workflow -- --foo --bar`
- # 2. Includes any WORKFLOW and EXPLICIT arguments.
- GLOBAL = (*WORKFLOW, '__GLOBAL_ARGUMENT__')
- # Captures private arguments intended for internal use.
- META = ('__META_ARGUMENT__',)
- # Captures GLOBAL and META arguments.
- ALL = (*GLOBAL, *META)
-
- def __lt__(self, other: 'ArgumentScope') -> bool:
- return len(self.value) < len(other.value)
-
- def __eq__(self, other: 'ArgumentScope') -> bool:
- return self.value == other.value
-
- def __hash__(self) -> Any:
- return hash(self.value)
-
-
-class ScopedArgumentParser:
- @classmethod
- def get_arguments(cls, scope: ArgumentScope) -> List[str]:
- return [
- arg
- for i, arg in list(enumerate(sys.argv))[1:]
- if sys.argv[i] not in ArgumentScope.ALL.value and (
- sys.argv[i - 1] not in ArgumentScope.ALL.value or sys.argv[i - 1] in scope.value
- )
- ]
-
- def get_default_arguments(self) -> List[str]:
- return self.get_arguments(self.default_argument_scope)
-
- @cached_property
- def default_argument_scope(self) -> ArgumentScope:
- return ArgumentScope[self.parse_args().default_argument_scope.upper()]
-
- def __init__(self, *argparse_args: Any, **argparse_kwargs: Any) -> None:
- self._scoped_parsers = {}
- self._argparse_init_args = argparse_args
- self._argparse_init_kwargs = argparse_kwargs
- self.add_argument(
- '--default_argument_scope',
- help=(
- 'The default scope of arguments to use for this task. '
- 'See the ArgumentScope class for additional information.'
- ),
- scope=ArgumentScope.META,
- choices = ['explicit', 'workflow', 'global'],
- default='explicit',
- )
-
- def _get_parser(self, scope: ArgumentScope) -> argparse.ArgumentParser:
- if scope not in self._scoped_parsers:
- self._scoped_parsers[scope] = argparse.ArgumentParser(
- *self._argparse_init_args,
- add_help=False,
- **self._argparse_init_kwargs
- )
- return self._scoped_parsers[scope]
-
- def add_argument(self, *argparse_args: Any, scope: ArgumentScope = None, **argparse_kwargs: Any) -> Any:
- return self._get_parser(
- self.default_argument_scope if scope is None else scope
- ).add_argument(*argparse_args, **argparse_kwargs)
-
- def parse_args(self, *argparse_args: Any, **argparse_kwargs: Any) -> argparse.Namespace:
- # TODO(chandarren): Handle `--help`.
- return argparse.Namespace(
- **reduce(lambda smaller_ns, larger_ns: {**vars(larger_ns), **smaller_ns}, [
- parser.parse_known_args(
- *argparse_args,
- args=self.get_arguments(scope),
- **argparse_kwargs
- )[0]
- for scope, parser
- in sorted(self._scoped_parsers.items())
- ], {})
- )
-
- def path_arg(self, type='file'):
- def arg(path):
- path = Path(path)
- if path.is_file() != (type == 'file') or path.is_dir() != (type == 'directory'):
- super(self).error(f'Path "{path}" is not a {type}!')
- return path
- return arg
-
-
-class FuchsiaTask:
- @classmethod
- def read_workflow_state(cls, file: Optional[Path] = None) -> Dict[str, Any]:
- workflow_state = {
- 'environment_variables': {},
- 'workflow': {
- 'halt_execution': False,
- },
- }
- workflow_state.update(json.loads(file.read_text()) if file else {})
- return workflow_state
-
- def __init__(
- self,
- *,
- task_name: str,
- is_final_task: bool,
- workflow_state: Dict[str, Any],
- ) -> None:
- self._task_name = task_name
- self._is_final_task = is_final_task
- self._workflow_state = workflow_state
-
- @contextmanager
- def apply_environment(self) -> None:
- original_environ = os.environ.copy()
- try:
- os.environ.update(self.workflow_state['environment_variables'] or {})
- yield
- finally:
- os.environ.clear()
- os.environ.update(original_environ)
-
- # Noop by default.
- @abstractmethod
- def run(self, parser: ScopedArgumentParser) -> None:
- pass
-
- @property
- def task_name(self) -> str:
- return self._task_name
-
- @property
- def is_final_task(self) -> bool:
- return self._is_final_task
-
- @property
- def workflow_state(self) -> Dict[str, Any]:
- return self._workflow_state
-
- def get_task_arguments(self, scope: ArgumentScope) -> List[str]:
- return ScopedArgumentParser.get_arguments(scope)
-
- @classmethod
- def main(cls, *, task_name: str=None, is_final_task: bool=None) -> None:
- parser = ScopedArgumentParser()
- parser.add_argument(
- '--workflow_task_name',
- help='The mnemonic associated with this task.',
- scope=ArgumentScope.META,
- **({} if task_name is None else {'default': task_name})
- )
- parser.add_argument(
- '--workflow_previous_state',
- help='A file to the previous workflow state.',
- scope=ArgumentScope.META,
- type=parser.path_arg(),
- required=False,
- )
- parser.add_argument(
- '--workflow_next_state',
- help='A file write to the next workflow state.',
- scope=ArgumentScope.META,
- type=parser.path_arg(None),
- )
- parser.add_argument(
- '--workflow_final_task',
- help='Whether this task is the root (final) task in the workflow.',
- action='store_true',
- scope=ArgumentScope.META,
- **({} if is_final_task is None else {'default': is_final_task})
- )
- workflow_args = parser.parse_args()
- task = cls(
- task_name=workflow_args.workflow_task_name,
- is_final_task=workflow_args.workflow_final_task,
- workflow_state=FuchsiaTask.read_workflow_state(
- workflow_args.workflow_previous_state
- ),
- )
- try:
- with task.apply_environment():
- task.run(parser)
- except TaskExecutionException as e:
- print(f'{Terminal.red("Fatal:")} {e}')
- if e.is_caught_failure:
- task.workflow_state['workflow']['halt_execution'] = True
- else:
- sys.exit(1)
- except KeyboardInterrupt:
- sys.exit(1)
- if workflow_args.workflow_next_state:
- workflow_args.workflow_next_state.write_text(json.dumps(task.workflow_state))
-
-if __name__ == '__main__':
- FuchsiaTask.main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/generate_symbols_dir.sh b/bazel_rules_fuchsia/fuchsia/tools/generate_symbols_dir.sh
deleted file mode 100755
index 7956903..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/generate_symbols_dir.sh
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/bin/bash
-
-# Generates debug symbols directory (_build_id) from a list of ids.txt files.
-#
-# Usage: generate_symbols_dir.sh <output path> <input files> ...
-#
-# The input files are a list of single-line ids.txt files in the format of "<build ID> <object_file_with_symbols>"
-#
-# This script should only be invoked by _fuchsia_package_impl in package.bzl.
-
-# Exits on any failure
-set -euf -o pipefail
-
-if [[ $# -lt 2 ]]; then
- echo >&2 "Error: invalid invocation of $0: $@. Expected >= 2 arguments."
- exit 1
-fi
-
-readonly output="$1"
-shift
-
-for input in "$@"; do
- # Skip empty file, which could mean not ELF file / no build_id info.
- if [[ ! -s "${input}" ]]; then
- continue
- fi
-
- content=$(<${input})
- # Split by the first space.
- # The content is following the ids.txt format: <build id> <elf_with_symbols>.
- build_id="${content%% *}"
- elf_with_symbols="${content#* }"
-
- # Convert to build-id directory path,
- # i.e. "de/adbeef.debug" for a "deadbeef" build id.
- build_id_path="${output}/${build_id::2}"
- debug_filename="${build_id:2}.debug"
-
- # Check whether the source file has symbols and debug_info.
- elf_info="$(file -L "${elf_with_symbols}")"
-
- # If the file is not stripped, add it to the output no matter whether it has debug_info.
- if [[ "${elf_info}" == *"not stripped"* ]]; then
- dest="${build_id_path}"
- mkdir -p "${build_id_path}"
- cp "${elf_with_symbols}" "${build_id_path}/${debug_filename}"
-
- # Warn if there's no debug_info.
- if [[ "${elf_info}" != *"with debug_info"* ]]; then
- echo >&2 "WARNING, no debug info in: \"${elf_with_symbols}\""
- fi
- # else
- # Otherwise, if the file is stripped (not "not stripped"), skip it.
- # echo >&2 "WARNING, binary is already stripped: \"${elf_with_symbols}\""
- fi
-done
-
-# Create an empty file if the output directory is empty, as bazel will ignore
-# empty directories
-if [[ -z "$(ls -A -- "$output")" ]]; then
- touch "${output}"/.ensure_there_is_one_file
-fi
diff --git a/bazel_rules_fuchsia/fuchsia/tools/json_comparator.py b/bazel_rules_fuchsia/fuchsia/tools/json_comparator.py
deleted file mode 100644
index 795610d..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/json_comparator.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-"""Tool to compare two json file against golden file regardless of order."""
-
-import argparse
-import json
-from pathlib import Path
-
-
-def parse_args():
- """Parses command-line arguments."""
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "--generated",
- help="Path to generated file",
- required=True,
- )
- parser.add_argument(
- "--golden",
- help="Path to the golden file",
- required=True,
- )
- return parser.parse_args()
-
-
-def sorting(item):
- if isinstance(item, dict):
- return sorted((key, sorting(values)) for key, values in item.items())
- if isinstance(item, list):
- return sorted(sorting(x) for x in item)
- return item
-
-
-def main():
- args = parse_args()
-
- with open(args.generated, "r") as f:
- gen = json.load(f)
- with open(args.golden, "r") as f:
- golden = json.load(f)
- if sorting(gen) != sorting(golden):
- print("Comparison failure!. \n Golden:\n" + str(golden) +
- "\nGenerated:\n" + str(gen))
- exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/licenses/BUILD.bazel b/bazel_rules_fuchsia/fuchsia/tools/licenses/BUILD.bazel
deleted file mode 100644
index cdfc040..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/licenses/BUILD.bazel
+++ /dev/null
@@ -1,66 +0,0 @@
-# Copyright 2021 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Tools supporting Fuchsia Bazel License rules.
-
-load("@rules_python//python:defs.bzl", "py_binary", "py_library")
-
-package(default_visibility = ["//visibility:public"])
-
-py_library(
- name = "common_types",
- srcs = ["common_types.py"],
-)
-
-py_library(
- name = "spdx_types",
- srcs = ["spdx_types.py"],
- deps = [":common_types"],
-)
-
-py_library(
- name = "classification_types",
- srcs = ["classification_types.py"],
- deps = [
- ":common_types",
- ":spdx_types",
- ],
-)
-
-py_binary(
- name = "generate_licenses_classification",
- srcs = ["generate_licenses_classification.py"],
- main = "generate_licenses_classification.py",
- deps = [
- ":classification_types",
- ":spdx_types",
- ],
-)
-
-py_binary(
- name = "generate_licenses_notice",
- srcs = ["generate_licenses_notice.py"],
- main = "generate_licenses_notice.py",
- python_version = "PY3",
- deps = [":spdx_types"],
-)
-
-py_binary(
- name = "generate_licenses_review",
- srcs = ["generate_licenses_review.py"],
- main = "generate_licenses_review.py",
- python_version = "PY3",
- deps = [
- ":classification_types",
- ":spdx_types",
- ],
-)
-
-py_binary(
- name = "generate_licenses_spdx",
- srcs = ["generate_licenses_spdx.py"],
- main = "generate_licenses_spdx.py",
- python_version = "PY3",
- deps = [":spdx_types"],
-)
diff --git a/bazel_rules_fuchsia/fuchsia/tools/licenses/classification_types.py b/bazel_rules_fuchsia/fuchsia/tools/licenses/classification_types.py
deleted file mode 100644
index f6e130a..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/licenses/classification_types.py
+++ /dev/null
@@ -1,920 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-"""Types for classifying licenses"""
-
-from collections import defaultdict
-import csv
-import dataclasses
-import json
-from fuchsia.tools.licenses.common_types import *
-from fuchsia.tools.licenses.spdx_types import *
-from hashlib import md5
-from typing import Any, Callable, ClassVar, Dict, Pattern, List
-
-# Work-around for b/258523163. We need to guarantee that at least one license is
-# identified by https://github.com/google/licenseclassifier/tree/main/tools/identify_license
-# or it exists with an error.
-# TODO(b/258523163): Remove once fixed
-b258523163_workaround = 'b258523163_workaround.txt'
-
-
-@dataclasses.dataclass(frozen=True)
-class IdentifiedSnippet:
- """Information about a single license snippet (text part of a large license text)"""
-
- # 'identified_as' value for unidentified snippets.
- UNIDENTIFIED_IDENTIFICATION: ClassVar[str] = "[UNIDENTIFIED]"
-
- identified_as: str
- confidence: float
- start_line: int
- end_line: int
-
- condition: str = None
- # Conditions from overriding rules
- overriden_conditions: List[str] = None
- # Dependents that were not matched by any rule
- dependents_unmatched_by_overriding_rules: List[str] = None
- # all rules that matched this IdentifiedSnippet
- overriding_rules: List["ConditionOverrideRule"] = None
-
- # verification results
- verified: bool = None
- verification_message: str = None
-
- # checksum for snippet text
- snippet_checksum: str = None
- snippet_text: str = None
-
- # A suggested override rule
- suggested_override_rule: "ConditionOverrideRule" = None
-
- def create_empty(extracted_text_lines) -> "IdentifiedSnippet":
- return IdentifiedSnippet(
- identified_as=IdentifiedSnippet.UNIDENTIFIED_IDENTIFICATION,
- confidence=1.0,
- start_line=1,
- end_line=len(extracted_text_lines) + 1)
-
- def from_identify_license_dict(
- dictionary: Dict[str, Any], location: Any) -> "IdentifiedSnippet":
- """
- Create a IdentifiedSnippet instance from a dictionary in the output format of
- https://github.com/google/licenseclassifier/tree/main/tools/identify_license.
-
- i.e.
- {
- "Name": str
- "Confidence": int or float
- "StartLine": int
- "EndLine": int
- }
- """
- r = DictReader(dictionary, location)
-
- # Confidence could be an int or a float. Convert to a float.
- try:
- confidence = r.get('Confidence', expected_type=float)
- except LicenseException:
- confidence = float(r.get('Confidence', expected_type=int))
-
- return IdentifiedSnippet(
- identified_as=r.get('Name'),
- confidence=confidence,
- start_line=r.get('StartLine', expected_type=int),
- end_line=r.get('EndLine', expected_type=int))
-
- def to_json_dict(self):
- # The fields are output in a certain order to produce a more readable output.
- out = {
- "identified_as": self.identified_as,
- "condition": self.condition,
- "verified": self.verified,
- }
-
- if self.verification_message:
- out["verification_message"] = self.verification_message
- if self.overriden_conditions:
- out["overriden_conditions"] = self.overriden_conditions
- if self.dependents_unmatched_by_overriding_rules:
- out["dependents_unmatched_by_overriding_rules"] = self.dependents_unmatched_by_overriding_rules
- if self.overriding_rules:
- out["overriding_rules"] = [
- r.to_json_dict() for r in self.overriding_rules
- ]
- if self.suggested_override_rule:
- out["suggested_override_rule"] = self.suggested_override_rule.to_json_dict(
- )
-
- out.update(
- {
- "confidence": self.confidence,
- "start_line": self.start_line,
- "end_line": self.end_line,
- "snippet_checksum": self.snippet_checksum,
- "snippet_text": self.snippet_text,
- })
- return out
-
- def from_json_dict(reader: DictReader) -> "IdentifiedSnippet":
- suggested_override_rule = None
- if reader.exists("suggested_override_rule"):
- suggested_override_rule = ConditionOverrideRule.from_json_dict(
- reader.get_reader("suggested_override_rule"), reader.location)
-
- overriding_rules = None
- if reader.exists("overriding_rules"):
- overriding_rules = [
- ConditionOverrideRule.from_json_dict(r, reader.location)
- for r in reader.get_readers_list("overriding_rules")
- ]
-
- return IdentifiedSnippet(
- identified_as=reader.get("identified_as"),
- condition=reader.get("condition"),
- verified=reader.get_or("verified", default=False),
- verification_message=reader.get_or(
- "verification_message", default=None),
- overriden_conditions=reader.get_or(
- "overriden_conditions", default=None, expected_type=list),
- dependents_unmatched_by_overriding_rules=reader.get_or(
- "dependents_unmatched_by_overriding_rules",
- default=None,
- expected_type=list),
- overriding_rules=overriding_rules,
- suggested_override_rule=suggested_override_rule,
- confidence=reader.get("confidence", expected_type=float),
- start_line=reader.get("start_line", expected_type=int),
- end_line=reader.get("end_line", expected_type=int),
- snippet_checksum=reader.get("snippet_checksum"),
- snippet_text=reader.get("snippet_text"),
- )
-
- def number_of_lines(self):
- return self.start_line - self.end_line + 1
-
- def add_snippet_text(self, lines: List[str]):
- text = '\n'.join(lines[self.start_line - 1:self.end_line])
- checksum = md5(text.encode('utf-8')).hexdigest()
- return dataclasses.replace(
- self, snippet_text=text, snippet_checksum=checksum)
-
- def set_conditions(self, policy: "ConditionsPolicy"):
- return dataclasses.replace(
- self, condition=policy.get_condition(self.identified_as))
-
- def override_conditions(
- self, license: "LicenseClassification",
- rules: List["ConditionOverrideRule"]):
- all_matching_rules = []
-
- new_conditions = set()
-
- remaining_dependents = set(license.dependents)
- for rule in rules:
- # Check that the in optimization in LicenseClassification was applied
- assert rule.match_license_names.matches(license.name)
-
- # Match identification, checksome, condition
- if not rule.match_identifications.matches(self.identified_as):
- continue
- if not rule.match_snippet_checksums.matches(self.snippet_checksum):
- continue
- if not rule.match_conditions.matches(self.condition):
- continue
-
- # Match dependents
- some_matching_dependents = rule.match_dependents.get_matches(
- license.dependents)
- if not some_matching_dependents:
- continue
-
- new_conditions.add(rule.override_condition_to)
- all_matching_rules.append(rule)
- for d in some_matching_dependents:
- if d in remaining_dependents:
- remaining_dependents.remove(d)
-
- if all_matching_rules:
- return dataclasses.replace(
- self,
- overriden_conditions=sorted(list(new_conditions)),
- dependents_unmatched_by_overriding_rules=sorted(
- list(remaining_dependents)),
- overriding_rules=all_matching_rules,
- )
- else:
- return self
-
- def verify_conditions(
- self, license: "LicenseClassification",
- allowed_conditions: Set[str]):
- """Sets the 'verified' and 'verification_message' fields"""
- verified = True
- message = None
- diallowed_override_conditions = []
- if self.overriden_conditions:
- diallowed_override_conditions = [
- c for c in self.overriden_conditions
- if c not in allowed_conditions
- ]
- if not self.overriding_rules:
- # Simple case: No overriding rules were involved.
- if self.condition not in allowed_conditions:
- verified = False
- message = f"'{self.condition}' condition is not an allowed"
- elif diallowed_override_conditions:
- # Some overriding rules were involved: Check their overriding conditions.
- rule_paths = [
- r.rule_file_path
- for r in self.overriding_rules
- if r.override_condition_to in diallowed_override_conditions
- ]
- verified = False
- message = f"The conditions {diallowed_override_conditions} are not allowed."\
- f" They were introduced by these rules: {rule_paths}."
- elif self.dependents_unmatched_by_overriding_rules:
- # Some license dependents didn't match any rule. Check the original
- # conditions.
- rule_paths = [r.rule_file_path for r in self.overriding_rules]
- if self.condition not in allowed_conditions:
- verified = False
- message = f"The overriding rules {rule_paths} changed the conditions to " \
- f"{self.overriden_conditions} but the rules don't match the dependencies " \
- f"{self.dependents_unmatched_by_overriding_rules} that remain with the " \
- f"condition '{self.condition} that is not allowed'."
-
- if verified:
- assert message == None
- suggested_override_rule = None
- else:
- assert message != None
- suggested_override_rule = ConditionOverrideRule.suggested_for_snippet(
- license, self, allowed_conditions)
-
- return dataclasses.replace(
- self,
- verified=verified,
- verification_message=message,
- suggested_override_rule=suggested_override_rule)
-
- def detailed_verification_message(
- self, license: "LicenseClassification") -> str:
- """Returns a very detailed verification failure message or None"""
-
- if self.verified:
- return None
-
- dependents_str = "\n".join([f" {d}" for d in license.dependents])
- license_links = "\n".join([f" {l}" for l in license.links])
- snippet = self.snippet_text
- if len(snippet) > 200:
- snippet = snippet[0:200] + "<trunctated>"
-
- message = f"""
-License '{license.name}' has a snippet identified as '{self.identified_as}'.
-
-License links:
-{license_links}
-
-The license is depended on by:
-{dependents_str}
-
-Snippet begin line: {self.start_line}
-Snippet end line: {self.end_line}
-Snippet checksum: {self.snippet_checksum}
-Snippet: <begin>
-{snippet}
-<end>
-
-Verification message:
-{self.verification_message}
-
-To fix this verification problem you should either:
-1. Remove the dependency on projects with this license in the dependent code bases.
-2. If the dependency is required and approved by the legal council of your project,
- you apply a local condition override, such as:
-{json.dumps(self.suggested_override_rule.to_json_dict(), indent=4)}
-"""
- return message
-
-
-@dataclasses.dataclass(frozen=True)
-class LicenseClassification:
- """Classification results for a single license"""
-
- license_id: str
- identifications: List[IdentifiedSnippet]
- name: str = None
- links: List[str] = None
- dependents: List[str] = None
-
- # license size & identification stats
- size_bytes: int = None
- size_lines: int = None
- unidentified_lines: int = None
-
- def to_json_dict(self):
- out = {
- "license_id": self.license_id,
- "name": self.name,
- "links": self.links,
- "dependents": self.dependents,
- "identifications": [m.to_json_dict() for m in self.identifications],
- "identification_stats":
- {
- "size_bytes": self.size_bytes,
- "size_lines": self.size_lines,
- "unidentified_lines": self.unidentified_lines,
- },
- }
-
- return out
-
- def from_json_dict(reader: DictReader) -> "LicenseClassification":
- identifications = [
- IdentifiedSnippet.from_json_dict(r)
- for r in reader.get_readers_list("identifications")
- ]
- stats_reader = reader.get_reader("identification_stats")
-
- return LicenseClassification(
- license_id=reader.get("license_id"),
- name=reader.get("name"),
- links=reader.get_string_list("links"),
- dependents=reader.get_string_list("dependents"),
- identifications=identifications,
- size_bytes=stats_reader.get_or(
- "size_bytes", default=None, expected_type=int,
- accept_none=True),
- size_lines=stats_reader.get_or(
- "size_lines", default=None, expected_type=int,
- accept_none=True),
- unidentified_lines=stats_reader.get_or(
- "unidentified_lines",
- default=None,
- expected_type=int,
- accept_none=True),
- )
-
- def add_license_information(self, index: SpdxIndex):
- spdx_license = index.get_license_by_id(self.license_id)
- snippet_lines = spdx_license.extracted_text_lines()
- identifications = [
- i.add_snippet_text(snippet_lines) for i in self.identifications
- ]
- links = []
- if spdx_license.cross_refs:
- links.extend(spdx_license.cross_refs)
- if spdx_license.see_also:
- links.extend(spdx_license.see_also)
- chains = index.dependency_chains_for_license(spdx_license.license_id)
- dependents = [">".join([p.name for p in chain]) for chain in chains]
- # Sort and dedup dependent chains: There might be duplicate chains since
- # the package names are not globally unique.
- dependents = sorted(set(dependents))
- return dataclasses.replace(
- self,
- identifications=identifications,
- name=spdx_license.name,
- links=links,
- dependents=dependents,
- )
-
- def compute_identification_stats(self, index: SpdxIndex):
- spdx_license = index.get_license_by_id(self.license_id)
-
- extracted_text = spdx_license.extracted_text
- extracted_lines = spdx_license.extracted_text_lines()
-
- lines_identified = 0
- for identification in self.identifications:
- lines_identified += identification.number_of_lines()
-
- return dataclasses.replace(
- self,
- size_bytes=len(extracted_text),
- size_lines=len(extracted_lines),
- unidentified_lines=len(extracted_lines) - lines_identified,
- )
-
- def _transform_identifications(self, function) -> "LicenseClassification":
- """Returns a copy of this object with the identifications transformed by function"""
- return dataclasses.replace(
- self, identifications=[function(i) for i in self.identifications])
-
- def set_conditions(self, policy: "ConditionsPolicy"):
- return self._transform_identifications(
- lambda x: x.set_conditions(policy))
-
- def override_conditions(self, rule_set: "ConditionOverrideRuleSet"):
- # Optimize by filtering rules that match the license name and any dependents
- relevant_rules = []
- for rule in rule_set.rules:
- if rule.match_license_names.matches(self.name):
- if rule.match_dependents.matches_any(self.dependents):
- relevant_rules.append(rule)
-
- if relevant_rules:
- return self._transform_identifications(
- lambda x: x.override_conditions(self, relevant_rules))
- else:
- return self
-
- def verify_conditions(self, allowed_conditions: Set[str]):
- return self._transform_identifications(
- lambda x: x.verify_conditions(self, allowed_conditions))
-
- def verification_errors(self) -> List[str]:
- out = []
- for i in self.identifications:
- msg = i.detailed_verification_message(self)
- if msg:
- out.append(msg)
- return out
-
-
-@dataclasses.dataclass(frozen=True)
-class LicensesClassifications:
- classifications_by_id: Dict[str, LicenseClassification]
-
- def create_empty() -> "LicenseClassification":
- return LicensesClassifications(classifications_by_id={})
-
- def from_identify_license_output_json(
- identify_license_output_path: str,
- license_paths_by_license_id: Dict[str,
- str]) -> "LicensesClassifications":
- json_output = json.load(open(identify_license_output_path, 'r'))
- # Expected results from https://github.com/google/licenseclassifier/tree/main/tools/identify_license
- # have the following json layout:
- # [
- # {
- # "Filepath": ...
- # "Classifications: [
- # {
- # "Name": ...
- # "Confidence": int or float
- # "StartLine": int
- # "EndLine": int
- # },
- # { ...},
- # ...
- # ]
- # },
- # { ... },
- # ...
- # ]
-
- results_by_file_path = {}
- for one_output in json_output:
- file_name = one_output['Filepath']
- if file_name == b258523163_workaround:
- continue
- results_by_file_path[file_name] = one_output['Classifications']
-
- identifications_by_license_id = defaultdict(list)
- for license_id, file_name in license_paths_by_license_id.items():
- if file_name in results_by_file_path.keys():
- for match_json in results_by_file_path[file_name]:
- identifications_by_license_id[license_id].append(
- IdentifiedSnippet.from_identify_license_dict(
- dictionary=match_json,
- location=identify_license_output_path))
- license_classifications = {}
- for license_id, identifications in identifications_by_license_id.items(
- ):
- license_classifications[license_id] = LicenseClassification(
- license_id=license_id, identifications=identifications)
-
- return LicensesClassifications(license_classifications)
-
- def to_json_list(self) -> List[Any]:
- output = []
- for license_id in sorted(self.classifications_by_id.keys()):
- output.append(self.classifications_by_id[license_id].to_json_dict())
- return output
-
- def to_json(self, json_file_path: str):
- with open(json_file_path, 'w') as output_file:
- json.dump(self.to_json_list(), output_file, indent=4)
-
- def from_json_list(
- input: List[Any], location: str) -> "LicensesClassifications":
- if not isinstance(input, List):
- raise LicenseException(
- f"Expected a list of classification json values, but got {type(input)}",
- location)
- classifications_by_id = {}
- for value in input:
- if not isinstance(value, dict):
- raise LicenseException(
- f"Expected json dict but got {type(input)}", location)
- value_reader = DictReader(value, location)
- classification = LicenseClassification.from_json_dict(value_reader)
- if classification.license_id in classifications_by_id:
- raise LicenseException(
- f"Multiple classifications with license_id '{classification.license_id}'",
- location)
- classifications_by_id[classification.license_id] = classification
-
- return LicensesClassifications(classifications_by_id)
-
- def from_json(json_file_path: str) -> "LicensesClassifications":
- with open(json_file_path, "r") as f:
- try:
- json_obj = json.load(f)
- except json.decoder.JSONDecodeError as e:
- raise LicenseException(
- f"Failed to parse json: {e}", json_file_path)
- return LicensesClassifications.from_json_list(
- json_obj, json_file_path)
-
- def _transform(
- self, function: Callable[[LicenseClassification], LicenseClassification]
- ) -> "LicensesClassifications":
- """Returns a copy of this object with the classifications transformed by function"""
- new = self.classifications_by_id.copy()
- for k, v in new.items():
- new[k] = function(v)
- return dataclasses.replace(self, classifications_by_id=new)
-
- def set_conditions(
- self, policy: "ConditionsPolicy") -> "LicensesClassifications":
- return self._transform(lambda x: x.set_conditions(policy))
-
- def add_classifications(
- self,
- to_add: List[LicenseClassification]) -> "LicensesClassifications":
- new = self.classifications_by_id.copy()
- for license_classification in to_add:
- license_id = license_classification.license_id
- assert license_id not in new, f"{license_id} already exists"
- new[license_id] = license_classification
- return dataclasses.replace(self, classifications_by_id=new)
-
- def add_licenses_information(self, spdx_index: SpdxIndex):
- return self._transform(lambda x: x.add_license_information(spdx_index))
-
- def compute_identification_stats(self, spdx_index: SpdxIndex):
- return self._transform(
- lambda x: x.compute_identification_stats(spdx_index))
-
- def override_conditions(
- self,
- rule_set: "ConditionOverrideRuleSet") -> "LicensesClassifications":
- return self._transform(lambda x: x.override_conditions(rule_set))
-
- def verify_conditions(
- self, allowed_conditions: Set[str]) -> "LicensesClassifications":
- return self._transform(
- lambda x: x.verify_conditions(allowed_conditions))
-
- def verification_errors(self):
- error_messages = []
- for c in self.classifications_by_id.values():
- error_messages.extend(c.verification_errors())
- return error_messages
-
- def identifications_count(self):
- c = 0
- for v in self.classifications_by_id.values():
- c += len(v.identifications)
- return c
-
- def failed_verifications_count(self):
- c = 0
- for v in self.classifications_by_id.values():
- for i in v.identifications:
- if not i.verified:
- c += 1
- return c
-
- def licenses_count(self):
- return len(self.classifications_by_id)
-
- def license_ids(self):
- return self.classifications_by_id.keys()
-
-
-@dataclasses.dataclass(frozen=True)
-class ConditionsPolicy:
- """
- A map of identification names (e.g. MIT, GPL) to policy condition names
- (e.g. notice, by_exception_only).
- """
- _condition_by_name: Dict[str, str]
- _default_condition: str
-
- def from_csv_file(csv_file_path, default_condition):
- """
- Creates a LicensesPolicy from a policy conditions csv file.
-
- The file has 2 columns: license (name), condition
- """
- map: Dict[str, str] = {}
-
- with open(csv_file_path, 'r') as read_obj:
- csv_dict_reader = csv.DictReader(read_obj)
- for row in csv_dict_reader:
- name = row["license"]
- assert name not in map, f"{name} already defined"
- map[name] = row["condition"]
- return ConditionsPolicy(map, default_condition)
-
- def get_condition(self, identification_name: str):
- """The condition associated with the name, or None"""
- if identification_name in self._condition_by_name:
- return self._condition_by_name[identification_name]
- else:
- return self._default_condition
-
-
-@dataclasses.dataclass(frozen=True)
-class AsterixStringExpression:
- """Utility for partial string matching (asterix matches)"""
- starts_with_asterix: bool
- ends_with_asterix: bool
- parts: List[str]
-
- def create(expression: str) -> "AsterixStringExpression":
- return AsterixStringExpression(
- starts_with_asterix=expression.startswith("*"),
- ends_with_asterix=expression.endswith("*"),
- parts=[p for p in expression.split("*") if p],
- )
-
- def matches(self, value) -> bool:
- if not self.parts:
- return True
- offset = 0
-
- if not self.starts_with_asterix and not value.startswith(self.parts[0]):
- return False
-
- for part in self.parts:
- next_match = value.find(part, offset)
- if next_match == -1:
- return False
- offset = next_match + len(part)
-
- return offset == len(value) or self.ends_with_asterix
-
-
-@dataclasses.dataclass(frozen=True)
-class StringMatcher:
- """
- A utility to perform override rule string matching.
-
- Supports exact and * matches.
- """
-
- all_expressions: List[str]
-
- exact_expressions: Set[str]
- asterix_expressions: List[AsterixStringExpression]
-
- def create(expressions: List[str]) -> "StringMatcher":
- assert isinstance(expressions, list)
- exact_expressions = set()
- asterix_expressions = []
- for e in expressions:
- assert isinstance(e, str)
- if "*" in e:
- asterix_expressions.append(AsterixStringExpression.create(e))
- else:
- exact_expressions.add(e)
-
- return StringMatcher(
- all_expressions=expressions,
- exact_expressions=exact_expressions,
- asterix_expressions=asterix_expressions)
-
- def create_match_everything() -> "StringMatcher":
- return StringMatcher.create(["*"])
-
- def to_json(self) -> Any:
- return self.all_expressions
-
- def matches(self, input: str) -> bool:
- if input in self.exact_expressions:
- return True
- for asterix_expression in self.asterix_expressions:
- if asterix_expression.matches(input):
- return True
- return False
-
- def get_matches(self, inputs: List[str]) -> List[str]:
- """
- Matches all the inputs against the internal expressions.
-
- Returns the ones that match or an empty list if none matched.
- """
- return [i for i in inputs if self.matches(i)]
-
- def matches_any(self, inputs: List[str]) -> bool:
- """
- Matches all the inputs against the internal expressions.
-
- Returns true if any inputs where matched.
- """
- if not self.all_expressions or not inputs:
- return False
- for input in inputs:
- if self.matches(input):
- return True
- return False
-
- def matches_all(self, inputs: List[str]) -> bool:
- """
- Matches all the inputs against the internal expressions.
-
- Returns true if all inputs where matched.
- """
- if not self.all_expressions or not inputs:
- return False
-
- for input in inputs:
- if not self.matches(input):
- return False
- return True
-
-
-@dataclasses.dataclass(frozen=True)
-class ConditionOverrideRule:
- """Rule for overriding a classified license condition"""
-
- # Path to the condition override rule.
- rule_file_path: str
- # Will override the condition to this condition
- override_condition_to: str
- bug: str
- # List facilitates easier to read multi-line comments in JSON.
- comment: List[str]
-
- # matching
- match_license_names: StringMatcher
- match_identifications: StringMatcher
- match_conditions: StringMatcher
- match_dependents: StringMatcher
- match_snippet_checksums: StringMatcher
-
- def from_json_dict(dictionary, rule_file_path) -> "ConditionOverrideRule":
- if isinstance(dictionary, DictReader):
- reader = dictionary
- else:
- reader = DictReader(dictionary=dictionary, location=rule_file_path)
-
- override_condition_to = reader.get("override_condition_to")
- bug = reader.get("bug")
- if not bug:
- raise LicenseException(
- "'bug' fields cannot be empty", rule_file_path)
- comment = reader.get("comment", expected_type=list)
-
- def verify_list_not_empty(list_value) -> str:
- if not list_value:
- return "list is empty"
- for v in list_value:
- if not v:
- return "empty value in list"
- return None
-
- criteria_reader = reader.get_reader("match_criteria")
-
- def read_required_matcher_field(name) -> StringMatcher:
- value = criteria_reader.get(
- name, expected_type=list, verify=verify_list_not_empty)
- return StringMatcher.create(value)
-
- match_license_names = read_required_matcher_field("license_names")
- match_conditions = read_required_matcher_field("conditions")
- match_dependents = read_required_matcher_field("dependents")
- match_identifications = read_required_matcher_field("identifications")
-
- # Checksum matching is optional except for unidentified snippets.
- match_snippet_checksums = criteria_reader.get_or(
- "snippet_checksums", expected_type=list, default=None)
-
- if match_identifications.matches(
- IdentifiedSnippet.UNIDENTIFIED_IDENTIFICATION):
- if not match_snippet_checksums:
- raise LicenseException(
- f"Rules that match license_names `{IdentifiedSnippet.UNIDENTIFIED_IDENTIFICATION}`"
- "must also set `snippet_checksum`", rule_file_path)
- if [s for s in match_snippet_checksums if "*" in s]:
- raise LicenseException(
- "Rules that license_names " \
- f" `{IdentifiedSnippet.UNIDENTIFIED_IDENTIFICATION}`"\
- " cannot have `*` expressions in `match_snippet_checksum`",
- rule_file_path)
- if match_snippet_checksums == None:
- match_snippet_checksums = StringMatcher.create_match_everything()
- else:
- match_snippet_checksums = StringMatcher.create(
- match_snippet_checksums)
-
- # If there is a rule_file_path value in the dict, use it instead.
- rule_file_path = reader.get_or("rule_file_path", default=rule_file_path)
-
- return ConditionOverrideRule(
- rule_file_path=rule_file_path,
- override_condition_to=override_condition_to,
- bug=bug,
- comment=comment,
- match_license_names=match_license_names,
- match_identifications=match_identifications,
- match_conditions=match_conditions,
- match_dependents=match_dependents,
- match_snippet_checksums=match_snippet_checksums,
- )
-
- def to_json_dict(self):
- # Fields are output in a certain order for better readability
- out = {}
- if self.rule_file_path:
- out["rule_file_path"] = self.rule_file_path
-
- out.update(
- {
- "override_condition_to": self.override_condition_to,
- "bug": self.bug,
- "comment": self.comment,
- "match_criteria":
- {
- "license_names":
- self.match_license_names.to_json(),
- "identifications":
- self.match_identifications.to_json(),
- "conditions":
- self.match_conditions.to_json(),
- "snippet_checksums":
- self.match_snippet_checksums.to_json(),
- "dependents":
- self.match_dependents.to_json(),
- },
- })
- return out
-
- def suggested_for_snippet(
- license: LicenseClassification, snippet: IdentifiedSnippet,
- allowed_conditions: Set[str]) -> "ConditionOverrideRule":
- """Creates a an override rule suggestion for the given license snippet"""
- dependents = license.dependents
- if snippet.dependents_unmatched_by_overriding_rules:
- dependents = snippet.dependents_unmatched_by_overriding_rules
- return ConditionOverrideRule(
- rule_file_path=None,
- override_condition_to="<CHOOSE ONE OF " +
- ", ".join([f"'{c}'" for c in allowed_conditions]) + ">",
- bug="<INSERT TICKET URL>",
- comment=["<INSERT DOCUMENTATION FOR OVERRIDE RULE>"],
- match_license_names=StringMatcher.create([license.name]),
- match_snippet_checksums=StringMatcher.create(
- [snippet.snippet_checksum]),
- match_identifications=StringMatcher.create([snippet.identified_as]),
- match_conditions=StringMatcher.create([snippet.condition]),
- match_dependents=StringMatcher.create(dependents))
-
-
-@dataclasses.dataclass(frozen=True)
-class ConditionOverrideRuleSet:
-
- rules: List[ConditionOverrideRule]
-
- def merge(
- self,
- other: "ConditionOverrideRuleSet") -> "ConditionOverrideRuleSet":
- new = list(self.rules)
- new.extend(other.rules)
- return dataclasses.replace(self, rules=new)
-
- def from_json(file_path: str) -> "ConditionOverrideRuleSet":
- with open(file_path, "r") as f:
- try:
- json_obj = json.load(f)
- except json.decoder.JSONDecodeError as e:
- raise LicenseException(f"Failed to parse json: {e}", file_path)
-
- if not isinstance(json_obj, list) and not isinstance(json_obj,
- dict):
- raise LicenseException(
- f"Expected List[dict] or dict at top-level json but found {type(json_obj)}",
- file_path)
-
- if isinstance(json_obj, dict):
- json_obj = [json_obj]
-
- rules = []
- for child_json in json_obj:
- if not isinstance(child_json, dict):
- raise LicenseException(
- f"Expected dict but found {type(child_json)}",
- file_path)
- rules.append(
- ConditionOverrideRule.from_json_dict(
- DictReader(child_json, file_path),
- rule_file_path=file_path))
-
- return ConditionOverrideRuleSet(rules)
diff --git a/bazel_rules_fuchsia/fuchsia/tools/licenses/common_types.py b/bazel_rules_fuchsia/fuchsia/tools/licenses/common_types.py
deleted file mode 100644
index 40d12dd..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/licenses/common_types.py
+++ /dev/null
@@ -1,135 +0,0 @@
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-"""Common definitions used in license processing"""
-
-import json
-from typing import Any, Callable, Dict, List, Type
-
-
-class LicenseException(Exception):
- """Exception class for exceptions in the license processing pipeline"""
-
- def __init__(self, message: str, location: str = None):
- if location:
- message = f"Error: {message} at {location}"
- super().__init__(self, message)
-
-
-class DictReader:
- """Helper class for reading keyed values from JSON dictionaries."""
-
- def __init__(self, dictionary: Dict[str, Any], location):
- if not isinstance(dictionary, dict):
- raise LicenseException(
- f"Expected dict but {type(dictionary)}", location)
- self._dict = dictionary
- self._location = location
-
- def _key_location(self, key):
- return f"{self._location}.{key}"
-
- @property
- def location(self):
- return self._location
-
- def exists(self, key) -> bool:
- """Returns whether `key` exists in the dictionary."""
- return key in self._dict
-
- def get(
- self,
- key: str,
- expected_type: Type = str,
- verify: Callable[[Any], str] = None):
- """Get the dictionary value by 'key'.
-
- Args:
- key: The key of the value.
- expected_type: The expected type of the value.
- verify: A function to verify the contents of the value.
- The function should return None if the value is verified or an error message str.
- """
- value = self.get_or(key, None, expected_type, verify)
- if value is None:
- raise LicenseException(
- f"Required key '{key}' is missing in dict '{self._dict}'",
- self.location)
- return value
-
- def get_or(
- self,
- key,
- default: Any,
- expected_type: Type = str,
- verify: Callable[[Any], str] = None,
- accept_none: bool = False):
- """Get the dictionary value by 'key' or fallback to a default value.
-
- Args:
- key: The key of the value.
- default: The value to return in case the key is not found.
- expected_type: The expected type of the value. Defaults to the type of the default value or str otherwise.
- verify: A function to verify the contents of the value.
- The function should return None if the value is verified or an error message str.
- accept_none: Whether None value is accepted.
- """
- if default is not None:
- expected_type = type(default)
-
- if key in self._dict:
- value = self._dict[key]
- if value is None and accept_none:
- return value
- if not isinstance(value, expected_type):
- raise LicenseException(
- f"Expected value of type {expected_type} but got {type(value)}",
- self._key_location(key))
- if verify:
- msg = verify(value)
- if msg:
- raise LicenseException(
- f"Unverified value '{value}': {msg}",
- self._key_location(key))
- return value
- return default
-
- def get_reader(self, key):
- value = self.get(key, expected_type=dict)
- if isinstance(value, dict):
- return DictReader(value, self._key_location(key))
- raise LicenseException(
- f"Expected dict for '{key}' but found {type(value)}",
- self._key_location(key))
-
- def get_readers_list(self, key, dedup=False):
- output = []
- for value in self.get_or(key, [], expected_type=list):
- if not isinstance(value, dict):
- raise LicenseException(
- f"Expected dict values in list but found {type(value)}",
- self._key_location(key))
- output.append(value)
- # Workaround for b/248101373#comment11. Some SPDX producers
- # produce duplicate json elements with the same SPDX Ref Ids.
- if dedup:
- unique_output = {}
- for value in output:
- dedup_key = json.dumps(value)
- if dedup_key not in unique_output:
- unique_output[dedup_key] = value
- output = list(unique_output.values())
- return [DictReader(v, self._key_location(key)) for v in output]
-
- def get_string_list(self, key) -> List[str]:
-
- def _verify_string_list(value):
- if not isinstance(value, list):
- return 'Expected list value'
- for v in value:
- if not isinstance(v, str):
- return f'Expected str value but got {type(v)}'
- return None
-
- return self.get_or(
- key, expected_type=list, default=[], verify=_verify_string_list)
diff --git a/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_classification.py b/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_classification.py
deleted file mode 100644
index 6057c03..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_classification.py
+++ /dev/null
@@ -1,275 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-'''Utility that classifies the licenses in an SPDX file.'''
-
-import argparse
-import os
-import subprocess
-from fuchsia.tools.licenses.classification_types import *
-from fuchsia.tools.licenses.spdx_types import *
-from sys import stderr
-
-
-def _log(*kwargs):
- print(*kwargs, file=stderr)
-
-
-def _prepare_license_files(license_files_dir: str,
- spdx_doc: SpdxDocument) -> Dict[str, str]:
- """Extract license texts in the spdx_doc into separate files"""
-
- # Reuse files for duplicate license texts to speed up classification
- file_by_unique_text: Dict[str, str] = {}
-
- license_files_by_id = {}
- for license in spdx_doc.extracted_licenses:
- id = license.license_id
- text = license.extracted_text
- if text in file_by_unique_text:
- file_path = file_by_unique_text[text]
- else:
- file_path = os.path.join(
- license_files_dir,
- f'license{len(file_by_unique_text.keys())}.txt')
- file_by_unique_text[text] = file_path
- with open(file_path, 'w') as license_file:
- license_file.write(license.extracted_text)
- license_files_by_id[id] = file_path
-
- _log(
- f"Identified {len(file_by_unique_text.keys())} unique license texts in"
- f" {len(spdx_doc.extracted_licenses)} extracted licenses: {file_by_unique_text.values()}"
- )
-
- return license_files_by_id
-
-
-def _invoke_identify_license(
- identify_license_path: str, license_files_dir: str,
- license_files_by_id: Dict[str, str]) -> LicensesClassifications:
- """Invokes identify_license tool, returning an LicensesClassifications."""
- identify_license_output_path = 'identify_license_out.json'
-
- license_paths = sorted(list(set(license_files_by_id.values())))
-
- for path in [identify_license_path, license_files_dir] + license_paths:
- assert os.path.exists(path), f'{path} doesn\'t exist'
-
- with open(b258523163_workaround, 'w') as f:
- f.write(_UNENCUMBERED_LICENSE)
-
- command = [
- identify_license_path,
- '-headers',
- f'-json={identify_license_output_path}',
- license_files_dir,
- b258523163_workaround,
- ]
-
- _log(f'identify_license invocation = {command}')
- subprocess.check_output(command)
-
- assert os.path.exists(
- identify_license_output_path
- ), f"{identify_license_output_path} doesn't exist"
-
- classifications = LicensesClassifications.from_identify_license_output_json(
- identify_license_output_path, license_files_by_id)
-
- _log(
- f'Identified {classifications.identifications_count()} identifications in {classifications.licenses_count()} licenses'
- )
-
- return classifications
-
-
-def _add_missing_identifications(
- spdx_doc: SpdxDocument,
- classifications: LicensesClassifications) -> LicensesClassifications:
- extra_classifications = []
- for l in spdx_doc.extracted_licenses:
- if l.license_id not in classifications.license_ids():
- identification = IdentifiedSnippet.create_empty(
- l.extracted_text_lines())
- extra_classifications.append(
- LicenseClassification(
- license_id=l.license_id, identifications=[identification]))
- return classifications.add_classifications(extra_classifications)
-
-
-def _load_override_rules(rule_paths: List[str]) -> ConditionOverrideRuleSet:
- rules = []
- for p in rule_paths:
- _log(f'Loading condition override rule {p}')
- rule_set = ConditionOverrideRuleSet.from_json(p)
- rules.extend(rule_set.rules)
- return ConditionOverrideRuleSet(rules)
-
-
-def _apply_policy_and_overrides(
- classification: LicensesClassifications,
- conditions_policy_file_path: str,
- default_condition: str,
- policy_override_rules_file_paths: List[str],
- allowed_conditions: List[str],
-) -> LicensesClassifications:
- conditions_policy = ConditionsPolicy.from_csv_file(
- conditions_policy_file_path, default_condition)
- classification = classification.set_conditions(conditions_policy)
-
- if policy_override_rules_file_paths:
- override_rules = _load_override_rules(policy_override_rules_file_paths)
- classification = classification.override_conditions(override_rules)
-
- classification = classification.verify_conditions(set(allowed_conditions))
-
- _log(
- f'{classification.failed_verifications_count()} of {classification.identifications_count()} identification failed verification'
- )
-
- return classification
-
-
-def _print_verification_errors(classification: LicensesClassifications):
- verification_messages = classification.verification_errors()
-
- if verification_messages:
- for i in range(0, len(verification_messages)):
- _log(f"==========================")
- _log(f"VERIFICATION MESSAGE {i+1}/{len(verification_messages)}:")
- _log(f"==========================")
- _log(verification_messages[i])
-
-
-def main():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- '--spdx_input',
- help='An SPDX json file containing all licenses to process.'
- 'The output of @rules_fuchsia `fuchsia_licenses_spdx`',
- required=True,
- )
- parser.add_argument(
- '--identify_license_bin',
- help='Path to the identify_license binary. '
- 'Expecting a binary with the same I/O as '
- 'https://github.com/google/licenseidentify_license/tree/main/tools/identify_license',
- required=True,
- )
- parser.add_argument(
- '--conditions_policy',
- help=
- 'A CSV file mapping license identification names to condition names',
- required=False,
- default=None,
- )
- parser.add_argument(
- '--policy_override_rules',
- help='Condition override rule files (JSON files)',
- # TODO(yaar): Document schema.
- nargs='*',
- required=False,
- default=[],
- )
- parser.add_argument(
- '--default_condition',
- help='Default condition for unmapped or unidentified licenses',
- required=False,
- default=None,
- )
-
- parser.add_argument(
- '--allowed_conditions',
- help='Conditions that are allowed',
- nargs='*',
- required=False,
- default=[],
- )
-
- parser.add_argument(
- '--fail_on_disallowed_conditions',
- help=
- 'The tool will fail when classifications map to conditions not in the allowed list',
- type=bool,
- required=False,
- default=False,
- )
-
- parser.add_argument(
- '--output_file',
- help='Where to write the output json',
- required=True,
- )
- args = parser.parse_args()
-
- _log(f'Got these args {args}!')
- spdx_input = args.spdx_input
-
- _log(f'Reading license info from {spdx_input}!')
- spdx_doc = SpdxDocument.from_json(spdx_input)
- spdx_index = SpdxIndex.create(spdx_doc)
-
- licenses_dir = 'input_licenses'
- os.mkdir(licenses_dir)
-
- license_files_by_id = _prepare_license_files(licenses_dir, spdx_doc)
-
- classification = _invoke_identify_license(
- identify_license_path=args.identify_license_bin,
- license_files_dir=licenses_dir,
- license_files_by_id=license_files_by_id)
-
- classification = _add_missing_identifications(spdx_doc, classification)
- classification = classification.compute_identification_stats(spdx_index)
- classification = classification.add_licenses_information(spdx_index)
-
- classification = _apply_policy_and_overrides(
- classification,
- conditions_policy_file_path=args.conditions_policy,
- default_condition=args.default_condition,
- policy_override_rules_file_paths=args.policy_override_rules,
- allowed_conditions=args.allowed_conditions,
- )
-
- output_json_path = args.output_file
- _log(f'Writing classification into {output_json_path}!')
- classification.to_json(output_json_path)
-
- if args.fail_on_disallowed_conditions:
- if classification.failed_verifications_count() > 0:
- _log("ERROR: Licenses verification failed.")
- _print_verification_errors(classification)
- exit(-1)
-
-
-# The text below is not a real license text.
-_UNENCUMBERED_LICENSE = '''
-This is free and unencumbered software released into the public domain.
-
-Anyone is free to copy, modify, publish, use, compile, sell, or distribute
-this software, either in source code form or as a compiled binary, for any
-purpose, commercial or non-commercial, and by any means.
-
-In jurisdictions that recognize copyright laws, the author or authors of this
-software dedicate any and all copyright interest in the software to the public
-domain. We make this dedication for the benefit of the public at large and to
-the detriment of our heirs and
-
-successors. We intend this dedication to be an overt act of relinquishment in
-perpetuity of all present and future rights to this software under copyright
-law.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
-ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-For more information, please refer to <http://unlicense.org/>
-'''
-
-if __name__ == '__main__':
- main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_notice.py b/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_notice.py
deleted file mode 100644
index 02f2f3d..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_notice.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-'''Utility that produces OSS licenses notice text file.'''
-
-import argparse
-import csv
-import os
-from sys import stderr
-from typing import Set, List
-import zipfile
-from fuchsia.tools.licenses.spdx_types import *
-
-
-def _log(*kwargs):
- print(*kwargs, file=stderr)
-
-
-def main():
- '''Parses arguments.'''
- parser = argparse.ArgumentParser()
- parser.add_argument(
- '--spdx_input',
- help='An SPDX json file containing all licenses to process.'
- ' The output of @rules_fuchsia `fuchsia_licenses_spdx`',
- required=True,
- )
- parser.add_argument(
- '--output_file',
- help='Where to write the notice text file.',
- required=True,
- )
- args = parser.parse_args()
-
- _log(f'Got these args {args}!')
-
- spdx_input = args.spdx_input
-
- _log(f'Reading license info from {spdx_input}!')
- spdx_doc = SpdxDocument.from_json(spdx_input)
- spdx_index = SpdxIndex.create(spdx_doc)
-
- output_path = args.output_file
- _log(f'Writing {output_path}...')
-
- licenses_by_unique_text = defaultdict(list)
- for license in spdx_doc.extracted_licenses:
- licenses_by_unique_text[license.extracted_text].append(license)
-
- packages_by_unique_copyright = defaultdict(list)
- for package in spdx_doc.packages:
- if package.copyright_text:
- packages_by_unique_copyright[package.copyright_text].append(package)
-
- with open(output_path, 'w') as notice:
-
- def write(text):
- notice.write(text)
-
- def write_delimiter():
- write(
- '================================================================================\n'
- )
-
- for unique_text, licenses in licenses_by_unique_text.items():
- write_delimiter()
- write('The following license text(s) applies to these projects:\n')
- unique_package_names = set()
- for license in licenses:
- for package in spdx_index.get_packages_by_license(license):
- unique_package_names.add(package.name)
- for package_name in sorted(list(unique_package_names)):
- write(f' • {package_name}\n')
-
- write('\n')
- write(unique_text)
- write('\n')
-
- for unique_text, packages in packages_by_unique_copyright.items():
- write_delimiter()
-
- write('The following copyright(s) applies to these projects:\n')
- unique_package_names = set([p.name for p in packages])
- for package_name in sorted(list(unique_package_names)):
- write(f' • {package_name}\n')
-
- write('\n')
- write(unique_text)
- write('\n')
-
-
-if __name__ == '__main__':
- main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_review.py b/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_review.py
deleted file mode 100644
index d6789b6..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_review.py
+++ /dev/null
@@ -1,214 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-'''Utility that produces OSS licenses compliance materials.'''
-
-import argparse
-import csv
-import os
-import shutil
-from sys import stderr
-from typing import Set, List
-import zipfile
-from fuchsia.tools.licenses.classification_types import *
-from fuchsia.tools.licenses.spdx_types import *
-
-
-def _log(*kwargs):
- print(*kwargs, file=stderr)
-
-
-def _dedup(input: List[str]) -> List[str]:
- return sorted(list(set(input)))
-
-
-def _write_summary(
- spdx_doc: SpdxDocument, index: SpdxIndex,
- classification: LicensesClassifications, output_path: str):
- with open(output_path, "w") as csvfile:
- writer = csv.DictWriter(
- csvfile,
- fieldnames=[
- "name",
- "identifications",
- "conditions",
- "overriden_conditions",
- "link",
- "tracking_issues",
- "comments",
- # The following 'debugging' fields begin with _ so can be easily
- # filtered/hidden/sorted once in a spreadsheet.
- "_spdx_license_id",
- "_dependents",
- "_detailed_identifications",
- "_detailed_overrides",
- "_size_bytes",
- "_size_lines",
- "_unidentified_lines",
- ])
- writer.writeheader()
-
- for license in spdx_doc.extracted_licenses:
- license_id = license.license_id
- dependents = [
- ">".join([p.name
- for p in path])
- for path in index.dependency_chains_for_license(
- license.license_id)
- ]
- links = []
- for l in license.cross_refs:
- links.append(l)
- for l in license.see_also:
- links.append(l)
- links = _dedup(links)
-
- identifications = []
- conditions = []
- overriden_conditions = []
- detailed_identifications = []
- detailed_overrides = []
- tracking_issues = []
- comments = []
- identification_stats = {}
- if license_id in classification.classifications_by_id:
- license_classification = classification.classifications_by_id[
- license_id]
- overriden_conditions = []
-
- identification_stats = {
- "_size_bytes":
- license_classification.size_bytes,
- "_size_lines":
- license_classification.size_lines,
- "_unidentified_lines":
- license_classification.unidentified_lines,
- }
-
- for i in license_classification.identifications:
- identifications.append(i.identified_as)
- conditions.append(i.condition)
-
- detailed_identifications.append(
- f"{i.identified_as} at lines {i.start_line}-{i.end_line}: {i.condition}"
- )
- if i.overriden_conditions:
- overriden_conditions.extend(i.overriden_conditions)
- if i.overriding_rules:
- for r in i.overriding_rules:
- detailed_overrides.append(
- f"{i.identified_as} ({i.condition}) at {i.start_line}-{i.end_line} overriden to ({r.override_condition_to}) by {r.rule_file_path}"
- )
- tracking_issues.append(r.bug)
- comments.append("\n".join(r.comment))
-
- row = {
- # License review columns
- "name":
- license.name,
- "link":
- "\n".join(_dedup(links)),
- "identifications":
- ",\n".join(_dedup(identifications)),
- "conditions":
- ",\n".join(_dedup(conditions)),
- "overriden_conditions":
- ",".join(_dedup(overriden_conditions)),
- "tracking_issues":
- "\n".join(_dedup(tracking_issues)),
- "comments":
- "\n=======\n".join(_dedup(comments)),
- # Advanced / debugging columns
- "_spdx_license_id":
- license_id,
- "_dependents":
- ",\n".join(_dedup(dependents)),
- "_detailed_identifications":
- ",\n".join(_dedup(detailed_identifications)),
- "_detailed_overrides":
- ",\n".join(_dedup(detailed_overrides)),
- }
- row.update(identification_stats)
-
- writer.writerow(row)
-
-
-def _zip_everything(output_dir_path: str, output_zip_path: str):
- with zipfile.ZipFile(output_zip_path, mode="w") as archive:
- for root, dirs, files in os.walk(output_dir_path):
- for file in files:
- archive.write(
- os.path.join(root, file),
- os.path.relpath(os.path.join(root, file), output_dir_path))
-
-
-def main():
- '''Parses arguments.'''
- parser = argparse.ArgumentParser()
- parser.add_argument(
- '--spdx_input',
- help='An SPDX json file containing all licenses to process.'
- ' The output of @rules_fuchsia `fuchsia_licenses_spdx`',
- required=True,
- )
- parser.add_argument(
- '--classification_input',
- help='A json file containing the results of'
- ' @rules_fuchsia `fuchsia_licenses_classification`',
- required=False,
- )
- parser.add_argument(
- '--output_file',
- help='Where to write the archive containing all the output files.',
- required=True,
- )
- parser.add_argument(
- '--output_dir',
- help='Where to write all the output files.',
- required=True,
- )
- args = parser.parse_args()
-
- _log(f'Got these args {args}!')
-
- spdx_input_path = args.spdx_input
- output_dir = args.output_dir
- classification_input_path = args.classification_input
-
- _log(f'Reading license info from {spdx_input_path}!')
- spdx_doc = SpdxDocument.from_json(spdx_input_path)
- spdx_index = SpdxIndex.create(spdx_doc)
-
- _log(f'Outputing all the files into {output_dir}!')
-
- spdx_doc.to_json(os.path.join(output_dir, "licenses.spdx.json"))
-
- if classification_input_path:
- shutil.copy(
- classification_input_path,
- os.path.join(output_dir, "classification.json"))
- classification = LicensesClassifications.from_json(
- classification_input_path)
- else:
- classification = LicensesClassifications.create_empty()
-
- extracted_licenses_dir = os.path.join(output_dir, "extracted_licenses")
- os.mkdir(extracted_licenses_dir)
- for license in spdx_doc.extracted_licenses:
- with open(os.path.join(extracted_licenses_dir,
- f"{license.license_id}.txt"),
- "w") as license_file:
- license_file.write(license.extracted_text)
-
- _write_summary(
- spdx_doc, spdx_index, classification,
- os.path.join(output_dir, "summary.csv"))
-
- output_file_path = args.output_file
- _log(f'Saving all the files into {output_file_path}!')
- _zip_everything(output_dir, output_file_path)
-
-
-if __name__ == '__main__':
- main()
diff --git a/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_spdx.py b/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_spdx.py
deleted file mode 100644
index d0d549a..0000000
--- a/bazel_rules_fuchsia/fuchsia/tools/licenses/generate_licenses_spdx.py
+++ /dev/null
@@ -1,208 +0,0 @@
-#!/usr/bin/env python3
-# Copyright 2022 The Fuchsia Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-'''Utility that produces an SPDX file containing all licenses used in a project'''
-
-import argparse
-import json
-from typing import Dict, List
-from sys import stderr
-from fuchsia.tools.licenses.spdx_types import *
-
-
-def _log(*kwargs):
- print(*kwargs, file=stderr)
-
-
-def _create_doc_from_licenses_used_json(
- licenses_used_path: str, root_package_name: str,
- document_namespace: str,
- licenses_cross_refs_base_url: str) -> SpdxDocument:
- """
- Populates the SPDX docuemnt with bazel license rules information.
-
- Populates the given SPDX document with information loaded
- from a JSON dict corresponding to a
- @rules_license//rules:gather_licenses_info.bzl JSON output.
- """
-
- _log(f'Reading {licenses_used_path}!')
- licenses_used_json = json.load(open(licenses_used_path, 'r'))
- assert isinstance(licenses_used_json, list)
- assert len(licenses_used_json) == 1
- licenses_used_dict = licenses_used_json[0]
- assert isinstance(licenses_used_dict, dict)
- assert 'licenses' in licenses_used_dict
- json_list = licenses_used_dict['licenses']
-
- package_id_factory = SpdxIdFactory.new_package_id_factory()
- license_id_factory = SpdxIdFactory.new_license_id_factory()
-
- packages = []
- describes = []
- relationships = []
- extracted_licenses = []
-
- root_package = SpdxPackage(
- spdx_id=package_id_factory.new_id(),
- name=root_package_name,
- copyright_text=None,
- license_concluded=None)
-
- packages.append(root_package)
- describes.append(root_package.spdx_id)
-
- for json_dict in json_list:
- bazel_package_name = json_dict['package_name']
- copyright_notice = json_dict['copyright_notice']
- license_text_file_path = json_dict['license_text']
-
- package_id = package_id_factory.new_id()
- license_id = None
- other_doc = None
- if license_text_file_path.endswith(".spdx.json"):
- other_doc = SpdxDocument.from_json(license_text_file_path)
- else:
- with open(license_text_file_path, 'r') as text_file:
- license_id = license_id_factory.new_id()
- _log(f'Extracting {license_text_file_path}!')
- cross_ref = licenses_cross_refs_base_url + license_text_file_path
- extracted_licenses.append(
- SpdxExtractedLicensingInfo(
- license_id=license_id,
- name=bazel_package_name,
- extracted_text=text_file.read(),
- cross_refs=[cross_ref]))
-
- packages.append(
- SpdxPackage(
- spdx_id=package_id,
- name=bazel_package_name,
- copyright_text=copyright_notice,
- license_concluded=SpdxLicenseExpression.create(license_id)
- if license_id else None,
- ))
-
- describes.append(package_id)
- relationships.append(
- SpdxRelationship(root_package.spdx_id, package_id, "CONTAINS"))
-
- if other_doc:
- _log(f'Merging {license_text_file_path}!')
- other_doc = other_doc.refactor_ids(
- package_id_factory, license_id_factory)
-
- other_doc_index = SpdxIndex.create(other_doc)
-
- relationships.extend(
- [
- SpdxRelationship(
- package_id, root_package.spdx_id, 'CONTAINS')
- for root_package in other_doc_index.get_root_packages()
- ])
- describes.extend(other_doc.describes)
- packages.extend(other_doc.packages)
- relationships.extend(other_doc.relationships)
- extracted_licenses.extend(other_doc.extracted_licenses)
-
- return SpdxDocument(
- file_path=None,
- name=root_package_name,
- namespace=document_namespace,
- creators=["Tool: fuchsia_licenses_spdx"],
- describes=describes,
- packages=packages,
- relationships=relationships,
- extracted_licenses=extracted_licenses,
- )
-
-
-def _merge_duplicate_licenses(document: SpdxDocument):
- """
- Returns a copy of the document with duplicate licenses merged.
-
- In large projects, many prebuilts have the same dependencies.
- Dedupping the extracted licenses helps optimize the automated
- analysis and manual reviews.
-
- Licenses are duplicate if their name and text are the same.
- The merged licenses will inherit the union of cross references
- and see-alsos from the originals to void data loss.
- """
-
- license_id_factory = SpdxIdFactory.new_license_id_factory()
- id_replacer = SpdxIdReplacer(license_id_factory)
- unique_licenses: dict[Tuple, SpdxExtractedLicensingInfo] = {}
- for license in document.extracted_licenses:
- # What makes a unique license are the name and the text:
- key = (license.name, license.extracted_text)
- if key not in unique_licenses:
- new_id = id_replacer.new_id(license.license_id)
- unique_licenses[key] = dataclasses.replace(
- license, license_id=new_id)
- else:
- unique_license = unique_licenses[key]
- id_replacer.map_id(license.license_id, unique_license.license_id)
- unique_licenses[key] = unique_license.merge_with(license)
-
- updated_licenses = list(unique_licenses.values())
- updated_packages = [
- p.replace_license_ids(id_replacer) for p in document.packages
- ]
-
- return dataclasses.replace(
- document,
- packages=updated_packages,
- extracted_licenses=updated_licenses)
-
-
-def main():
- '''Parses arguments.'''
- parser = argparse.ArgumentParser()
- parser.add_argument(
- '--licenses_used',
- help='JSON file containing all licenses to analyze.'
- ' The output of @rules_license//rules:gather_licenses_info.bzl',