Allow flags and targets to be specified as maps or sets (#1730)

This is a second attempt at #1727, now with tests (until now, bazelci.py
had no tests!)

Motivation: https://github.com/bazelbuild/stardoc/pull/184

We often want to specify a base list of flags/targets which can be
augmented on "weird" platforms (Windows, perhaps Mac). But to use the
YAML `<<:` merge key, the entities merged must be maps or sets, not
lists.

To do this, we can allow *_flags and *_targets to be maps or sets - but
we must take care to transform them to lists when processing, so that
list concatenation etc. operators still work.
diff --git a/buildkite/README.md b/buildkite/README.md
index 948f59c..d6781b6 100644
--- a/buildkite/README.md
+++ b/buildkite/README.md
@@ -190,6 +190,42 @@
     - ":clwb_tests"
 ```
 
+### Sharing Configuration Between Tasks
+
+You can define common configurations and share them between tasks using `*aliases` and the [`<<:` merge key](https://yaml.org/type/merge.html). YAML allows merging maps and sets, but not lists; to merge flags or targets, instead of a list, represent them as a map from strings to null:
+
+```yaml
+# This is a map from strings to null, not a list, to allow merging into windows.build_flags and windows.test_flags
+.common_flags: &common_flags
+  ? "--incompatible_disable_starlark_host_transitions"
+  ? "--enable_bzlmod"
+
+.common_task_config: &common_task_config
+  build_flags: *common_flags
+  build_targets:
+    - "//..."
+  test_flags: *common_flags
+  test_targets:
+    - "//tests/..."
+
+tasks:
+  ubuntu1804:
+    <<: *common_task_config
+  ubuntu2004:
+    <<: *common_task_config
+  windows:
+    <<: *common_task_config
+    # These are maps from strings to null, not lists, to allow merging
+    build_flags:
+      <<: *common_flags
+      ? "--noexperimental_repository_cache_hardlinks"
+    test_flags:
+      <<: *common_flags
+      ? "--noexperimental_repository_cache_hardlinks"
+```
+
+Instead of a map from string to null, you could use a set (via `!!set`); however, sets are unordered, which makes them unsuitable for target lists that use the negation operator.
+
 ### Specifying a Display Name
 
 Each task may have an optional display name that can include Emojis. This feature is especially useful if you have several tasks that run on the same platform, but use different Bazel binaries.
diff --git a/buildkite/bazelci.py b/buildkite/bazelci.py
index 0e4fa2d..874e086 100755
--- a/buildkite/bazelci.py
+++ b/buildkite/bazelci.py
@@ -1209,7 +1209,7 @@
             )
         ]
 
-    flags = task_config.get(task_config_key) or []
+    flags = list(task_config.get(task_config_key, []))
     flags += json_profile_flags
     flags += capture_corrupted_outputs_flags
     # We have to add --test_env flags to `build`, too, otherwise Bazel
@@ -2191,10 +2191,10 @@
 ):
     print_collapsed_group(":dart: Calculating targets")
 
-    build_targets = [] if test_only else task_config.get("build_targets", [])
-    test_targets = [] if build_only else task_config.get("test_targets", [])
-    coverage_targets = [] if (build_only or test_only) else task_config.get("coverage_targets", [])
-    index_targets = [] if (build_only or test_only) else task_config.get("index_targets", [])
+    build_targets = [] if test_only else list(task_config.get("build_targets", []))
+    test_targets = [] if build_only else list(task_config.get("test_targets", []))
+    coverage_targets = [] if (build_only or test_only) else list(task_config.get("coverage_targets", []))
+    index_targets = [] if (build_only or test_only) else list(task_config.get("index_targets", []))
 
     index_targets_query = (
         None if (build_only or test_only) else task_config.get("index_targets_query", None)
diff --git a/buildkite/bazelci_test.py b/buildkite/bazelci_test.py
new file mode 100755
index 0000000..d8bec98
--- /dev/null
+++ b/buildkite/bazelci_test.py
@@ -0,0 +1,176 @@
+#!/usr/bin/env python3
+#
+# Copyright 2023 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+
+os.environ["BUILDKITE_ORGANIZATION_SLUG"] = "bazel"
+os.environ["BUILDKITE_PIPELINE_SLUG"] = "test"
+
+import bazelci
+import unittest
+import yaml
+
+
+class CalculateFlags(unittest.TestCase):
+    _CONFIGS = yaml.safe_load(
+        """
+.base_flags: &base_flags
+  ? "--enable_a"
+  ? "--enable_b"
+
+tasks:
+  basic:
+    build_flags:
+      - "--enable_x"
+      - "--enable_y"
+    build_targets:
+      - "//..."
+  json_profile:
+    build_flags:
+      - "--enable_x"
+      - "--enable_y"
+    build_targets:
+      - "//..."
+    include_json_profile:
+      - build
+  capture_corrupted:
+    build_flags:
+      - "--enable_x"
+      - "--enable_y"
+    build_targets:
+      - "//..."
+    capture_corrupted_outputs:
+      - build
+  no_flags:
+    test_targets:
+      - "//..."
+  merge_flags:
+    build_flags:
+      <<: *base_flags
+      ? "--enable_z"
+      ? "--enable_w"
+    build_targets:
+      - "//..."
+    """
+    )
+
+    def test_basic_functionality(self):
+        tasks = self._CONFIGS.get("tasks")
+        flags, json_profile_out, capture_corrupted_outputs_dir = bazelci.calculate_flags(
+            tasks.get("basic"), "build_flags", "build", "/tmp", ["HOME"]
+        )
+        self.assertEqual(flags, ["--enable_x", "--enable_y", "--test_env=HOME"])
+        self.assertEqual(json_profile_out, None)
+        self.assertEqual(capture_corrupted_outputs_dir, None)
+
+    def test_json_profile(self):
+        tasks = self._CONFIGS.get("tasks")
+        flags, json_profile_out, capture_corrupted_outputs_dir = bazelci.calculate_flags(
+            tasks.get("json_profile"), "build_flags", "build", "/tmp", ["HOME"]
+        )
+        self.assertEqual(
+            flags,
+            ["--enable_x", "--enable_y", "--profile=/tmp/build.profile.gz", "--test_env=HOME"],
+        )
+        self.assertEqual(json_profile_out, "/tmp/build.profile.gz")
+
+    def test_capture_corrupted(self):
+        tasks = self._CONFIGS.get("tasks")
+        flags, json_profile_out, capture_corrupted_outputs_dir = bazelci.calculate_flags(
+            tasks.get("capture_corrupted"), "build_flags", "build", "/tmp", ["HOME"]
+        )
+        self.assertEqual(
+            flags,
+            [
+                "--enable_x",
+                "--enable_y",
+                "--experimental_remote_capture_corrupted_outputs=/tmp/build_corrupted_outputs",
+                "--test_env=HOME",
+            ],
+        )
+        self.assertEqual(capture_corrupted_outputs_dir, "/tmp/build_corrupted_outputs")
+
+    def test_no_flags_in_config(self):
+        tasks = self._CONFIGS.get("tasks")
+        flags, json_profile_out, capture_corrupted_outputs_dir = bazelci.calculate_flags(
+            tasks.get("no_flags"), "build_flags", "build", "/tmp", ["HOME"]
+        )
+        self.assertEqual(flags, ["--test_env=HOME"])
+
+    def test_merge_flags(self):
+        tasks = self._CONFIGS.get("tasks")
+        flags, json_profile_out, capture_corrupted_outputs_dir = bazelci.calculate_flags(
+            tasks.get("merge_flags"), "build_flags", "build", "/tmp", ["HOME"]
+        )
+        self.assertEqual(
+            flags,
+            ["--enable_a", "--enable_b", "--enable_z", "--enable_w", "--test_env=HOME"],
+        )
+
+
+class CalculateTargets(unittest.TestCase):
+    _CONFIGS = yaml.safe_load(
+        """
+.base_targets: &base_targets
+  ? "//..."
+  ? "-//experimental/..."
+
+tasks:
+  basic:
+    build_targets:
+      - "//..."
+      - "-//bad/..."
+  merge:
+    build_targets:
+      <<: *base_targets
+      ? "//experimental/good/..."
+    """
+    )
+
+    def test_basic_functionality(self):
+        tasks = self._CONFIGS.get("tasks")
+        build_targets, test_targets, coverage_targets, index_targets = bazelci.calculate_targets(
+            tasks.get("basic"),
+            "bazel",
+            build_only=False,
+            test_only=False,
+            workspace_dir="/tmp",
+            ws_setup_func=None,
+            git_commit="abcd",
+            test_flags=[],
+        )
+        self.assertEqual(build_targets, ["//...", "-//bad/..."])
+        self.assertEqual(test_targets, [])
+        self.assertEqual(coverage_targets, [])
+        self.assertEqual(index_targets, [])
+
+    def test_merge(self):
+        tasks = self._CONFIGS.get("tasks")
+        build_targets, test_targets, coverage_targets, index_targets = bazelci.calculate_targets(
+            tasks.get("merge"),
+            "bazel",
+            build_only=False,
+            test_only=False,
+            workspace_dir="/tmp",
+            ws_setup_func=None,
+            git_commit="abcd",
+            test_flags=[],
+        )
+        self.assertEqual(build_targets, ["//...", "-//experimental/...", "//experimental/good/..."])
+
+
+if __name__ == "__main__":
+    unittest.main()