# Copyright 2021 The Pigweed Authors
#
# 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
#
#     https://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("//build_overrides/pigweed.gni")

# Mirrors a directory structure to the output directory.
#
# This is similar to a GN copy target, with some differences:
#
#   - The outputs list is generated by the template based on the source_root and
#     directory arguments, rather than using source expansion.
#   - The source_root argument can be used to trim prefixes from source files.
#   - pw_mirror_tree uses hard links instead of copies for efficiency.
#
# Args:
#
#   directory: Output directory for the files.
#   sources: List of files to mirror to the output directory.
#   source_root: Root path for sources; defaults to ".".
#
template("pw_mirror_tree") {
  assert(defined(invoker.sources), "'sources' must be provided")
  assert(defined(invoker.directory) && invoker.directory != "",
         "The output path must be specified as 'directory'")

  if (defined(invoker.source_root)) {
    _root = invoker.source_root
  } else {
    _root = "."
  }

  _deps = []
  if (defined(invoker.deps)) {
    _deps += invoker.deps
  }

  _public_deps = []
  if (defined(invoker.public_deps)) {
    _public_deps += invoker.public_deps
  }

  _copy_deps = []

  foreach(source, invoker.sources) {
    _stripped_source = rebase_path(source, _root)
    _subtarget_name =
        string_replace("${target_name}_${_stripped_source}", "/", ".")

    copy(_subtarget_name) {
      sources = [ source ]
      outputs = [ "${invoker.directory}/${_stripped_source}" ]
      deps = _deps
      public_deps = _public_deps
    }
    _copy_deps += [ ":${_subtarget_name}" ]
  }

  group(target_name) {
    public_deps = _copy_deps
  }
}
