Support disting testonly deps.

Setting testonly = True on a target requires all of its rdeps to also
set testonly.

This means that the rdeps dist targets also need to set distonly.

Test: b build //build/bazel_common_rules/dist:all
Change-Id: I20e5991cd07190d3a73d28e92ed83d31b19bec5d
diff --git a/dist/BUILD b/dist/BUILD
index e956a31..3f531ef 100644
--- a/dist/BUILD
+++ b/dist/BUILD
@@ -21,3 +21,17 @@
         "//bionic/libdl",
     ],
 )
+
+# For testing that `testonly` deps can be dist'd.
+genrule(
+    name = "testonly_sample",
+    testonly = True,
+    outs = ["testonly.txt"],
+    cmd = "touch $@",
+)
+
+copy_to_dist_dir(
+    name = "dist_testonly_sample",
+    testonly = True,
+    data = [":testonly_sample"],
+)
diff --git a/dist/dist.bzl b/dist/dist.bzl
index cb60d99..3d3ac66 100644
--- a/dist/dist.bzl
+++ b/dist/dist.bzl
@@ -69,6 +69,7 @@
         allow_duplicate_filenames = None,
         mode_overrides = None,
         log = None,
+        testonly = False,
         **kwargs):
     """A dist rule to copy files out of Bazel's output directory into a custom location.
 
@@ -134,6 +135,10 @@
         log: If specified, `--log <log>` is provided to the script by default. This sets the
           default log level of the script.
 
+        testonly: If enabled, testonly will also be set on the internal targets
+          for Bazel analysis to succeed due to the nature of testonly enforcement
+          on reverse dependencies.
+
           See `dist.py` for allowed values and the default value.
         kwargs: Additional attributes to the internal rule, e.g.
           [`visibility`](https://docs.bazel.build/versions/main/visibility.html).
@@ -168,6 +173,7 @@
         name = name + "_dist_manifest",
         data = data,
         archives = archives,
+        testonly = testonly,
     )
 
     copy_file(
@@ -186,11 +192,13 @@
         python_version = "PY3",
         visibility = ["//visibility:public"],
         data = [name + "_dist_manifest"],
+        testonly = testonly,
         args = default_args,
     )
 
     embedded_exec(
         name = name,
         actual = name + "_internal",
+        testonly = testonly,
         **kwargs
     )