# Copyright 2015 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

template("buildflag_header") {
  action(target_name) {
    script = "write_buildflag_header.py"

    if (defined(invoker.header_dir)) {
      header_file = "${invoker.header_dir}/${invoker.header}"
    } else {
      # Compute the path from the root to this file.
      header_file = rebase_path(".", "//") + "/${invoker.header}"
    }

    outputs = [ "$root_gen_dir/$header_file" ]

    # Write flags to a file just in case they exceed the system's maximum
    # command line length.
    #
    # Using write_file instead of response_file_contents to avoid a spurious
    # rule variable cycle in generated command in Ninja.
    #
    # See more details from the following bugs:
    # * https://bugs.fuchsia.dev/p/fuchsia/issues/detail?id=76068
    # * https://github.com/ninja-build/ninja/issues/1966
    flags = [ "--flags" ]
    if (defined(invoker.flags)) {
      flags += invoker.flags
    }
    flags_file = "${root_gen_dir}/${header_file}.flags"
    write_file(flags_file, flags)
    inputs = [ flags_file ]

    args = [
      "--output",
      header_file,  # Not rebased, Python script puts it inside gen-dir.
      "--rulename",
      get_label_info(":$target_name", "label_no_toolchain"),
      "--gen-dir",
      rebase_path(root_gen_dir, root_build_dir),
      "--definitions",
      rebase_path(flags_file, root_build_dir),
    ]

    forward_variables_from(invoker,
                           [
                             "deps",
                             "public_deps",
                             "testonly",
                             "visibility",
                           ])

    public_deps = [ ":buildflag_header_h" ]
  }
}
