From fb3ef6e45d1487b41f621f9682043e9312cd4478 Mon Sep 17 00:00:00 2001 From: Greg Magolan Date: Sat, 7 Jan 2023 11:26:27 -0800 Subject: [PATCH] feat: improved copy_to_directory performance & globbing support using copy_to_directory_bin_action (#311) --- docs/copy_to_directory.md | 70 ++++- e2e/copy_to_directory/BUILD.bazel | 7 +- lib/BUILD.bazel | 5 + lib/copy_to_directory.bzl | 7 +- lib/extensions.bzl | 2 + lib/private/copy_to_directory.bzl | 243 ++++++++---------- lib/private/copy_to_directory_toolchain.bzl | 188 ++++++++++++++ lib/private/docs/BUILD.bazel | 5 + lib/repositories.bzl | 26 ++ lib/tests/copy_to_directory/BUILD.bazel | 36 ++- .../copy_to_directory_bin_action/BUILD.bazel | 4 +- tools/copy_to_directory_mirror_release.sh | 31 +++ 12 files changed, 446 insertions(+), 178 deletions(-) create mode 100644 lib/private/copy_to_directory_toolchain.bzl create mode 100755 tools/copy_to_directory_mirror_release.sh diff --git a/docs/copy_to_directory.md b/docs/copy_to_directory.md index 48f880c..ae3fb57 100644 --- a/docs/copy_to_directory.md +++ b/docs/copy_to_directory.md @@ -13,7 +13,7 @@ the `root_paths`, `include_srcs_patters`, `exclude_srcs_patters` and `replace_pr
 copy_to_directory(name, allow_overwrites, exclude_prefixes, exclude_srcs_packages,
                   exclude_srcs_patterns, include_external_repositories, include_srcs_packages,
-                  include_srcs_patterns, out, replace_prefixes, root_paths, srcs)
+                  include_srcs_patterns, out, replace_prefixes, root_paths, srcs, verbose)
 
@@ -25,16 +25,17 @@ copy_to_directory(name, name | A unique name for this target. | Name | required | | | allow_overwrites | If True, allow files to be overwritten if the same output file is copied to twice.

If set, then the order of srcs matters as the last copy of a particular file will win.

This setting has no effect on Windows where overwrites are always allowed. | Boolean | optional | False | -| exclude_prefixes | List of path prefixes (with glob support) to exclude from output directory.

DEPRECATED: use exclude_srcs_patterns instead

Glob patterns **, * and ? are supported. See glob_match documentation for more details on how to use glob patterns: https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md.

Files and directories in srcs are not copied to the output directory if their output directory path, after applying root_paths, starts with or fully matches one of the patterns specified.

Patterns do not look into files within source directory or generated directory (TreeArtifact) targets since matches are performed in Starlark. To use include_srcs_patterns on files within directories you can use the make_directory_paths helper to specify individual files inside directories in srcs. This restriction may be fixed in a future release by performing matching inside the copy action instead of in Starlark.

Forward slashes (/) should be used as path separators.

Files and directories that do not have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | [] | -| exclude_srcs_packages | List of Bazel packages (with glob support) to exclude from output directory.

Glob patterns **, * and ? are supported. See glob_match documentation for more details on how to use glob patterns: https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md.

Files and directories in srcs are not copied to the output directory if the Bazel package of the file or directory matches one of the patterns specified.

Forward slashes (/) should be used as path separators.

A "." value means exclude srcs that are in the target's package. It expands to the target's package path (ctx.label.package). This will be an empty string "" if the target is in the root package.

A "./**" value means exclude srcs that are in subpackages of the target's package. It expands to the target's package path followed by a slash and a globstar ("{}/**".format(ctx.label.package)). If the target's package is the root package, "./**" expands to ["?*", "?*/**"] instead.

Files and directories that have do not have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | [] | -| exclude_srcs_patterns | List of paths (with glob support) to exclude from output directory.

Glob patterns **, * and ? are supported. See glob_match documentation for more details on how to use glob patterns: https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md.

Files and directories in srcs are not copied to the output directory if their output directory path, after applying root_paths, matches one of the patterns specified.

Patterns do not look into files within source directory or generated directory (TreeArtifact) targets since matches are performed in Starlark. To use include_srcs_patterns on files within directories you can use the make_directory_paths helper to specify individual files inside directories in srcs. This restriction may be fixed in a future release by performing matching inside the copy action instead of in Starlark.

Forward slashes (/) should be used as path separators.

Files and directories that do not have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | [] | -| include_external_repositories | List of external repository names (with glob support) to include in the output directory.

Glob patterns **, * and ? are supported. See glob_match documentation for more details on how to use glob patterns: https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md.

Files from external repositories are only copied into the output directory if the external repository they come from matches one of the external repository patterns specified.

When copied from an external repository, the file path in the output directory defaults to the file's path within the external repository. The external repository name is _not_ included in that path.

For example, the following copies @external_repo//path/to:file to path/to/file within the output directory.

         copy_to_directory(             name = "dir",             include_external_repositories = ["external_*"],             srcs = ["@external_repo//path/to:file"],         )         


Files and directories that come from matching external are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. The external repository name of the file or directory from an external repository is not included in the output directory path and is considered in subsequent filters and transformations.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | [] | -| include_srcs_packages | List of Bazel packages (with glob support) to include in output directory.

Glob patterns **, * and ? are supported. See glob_match documentation for more details on how to use glob patterns: https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md.

Files and directories in srcs are only copied to the output directory if the Bazel package of the file or directory matches one of the patterns specified.

Forward slashes (/) should be used as path separators.

A "." value means include srcs that are in the target's package. It expands to the target's package path (ctx.label.package). This will be an empty string "" if the target is in the root package.

A "./**" value means include srcs that are in subpackages of the target's package. It expands to the target's package path followed by a slash and a globstar ("{}/**".format(ctx.label.package)). If the target's package is the root package, "./**" expands to ["?*", "?*/**"] instead.

Defaults to ["**"] which includes sources from all packages.

Files and directories that have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | ["**"] | -| include_srcs_patterns | List of paths (with glob support) to include in output directory.

Glob patterns **, * and ? are supported. See glob_match documentation for more details on how to use glob patterns: https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md.

Files and directories in srcs are only copied to the output directory if their output directory path, after applying root_paths, matches one of the patterns specified.

Patterns do not look into files within source directory or generated directory (TreeArtifact) targets since matches are performed in Starlark. To use include_srcs_patterns on files within directories you can use the make_directory_paths helper to specify individual files inside directories in srcs. This restriction may be fixed in a future release by performing matching inside the copy action instead of in Starlark.

Forward slashes (/) should be used as path separators.

Defaults to ["**"] which includes all sources.

Files and directories that have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | ["**"] | +| exclude_prefixes | List of path prefixes (with glob support) to exclude from output directory.

DEPRECATED: use exclude_srcs_patterns instead

Files in srcs are not copied to the output directory if their output directory path, after applying root_paths, starts with or fully matches one of the patterns specified.

Forward slashes (/) should be used as path separators.

Files that do not have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Glob patterns are supported. Standard wildcards (globbing patterns) plus the ** doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | [] | +| exclude_srcs_packages | List of Bazel packages (with glob support) to exclude from output directory.

Files in srcs are not copied to the output directory if the Bazel package of the file matches one of the patterns specified.

Forward slashes (/) should be used as path separators. A first character of "." will be replaced by the target's package path.

Files that have do not have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Glob patterns are supported. Standard wildcards (globbing patterns) plus the ** doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | [] | +| exclude_srcs_patterns | List of paths (with glob support) to exclude from output directory.

Files in srcs are not copied to the output directory if their output directory path, after applying root_paths, matches one of the patterns specified.

Forward slashes (/) should be used as path separators.

Files that do not have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Glob patterns are supported. Standard wildcards (globbing patterns) plus the ** doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | [] | +| include_external_repositories | List of external repository names (with glob support) to include in the output directory.

Files from external repositories are only copied into the output directory if the external repository they come from matches one of the external repository patterns specified.

When copied from an external repository, the file path in the output directory defaults to the file's path within the external repository. The external repository name is _not_ included in that path.

For example, the following copies @external_repo//path/to:file to path/to/file within the output directory.

         copy_to_directory(             name = "dir",             include_external_repositories = ["external_*"],             srcs = ["@external_repo//path/to:file"],         )         


Files that come from matching external are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. The external repository name of the file from an external repository is not included in the output directory path and is considered in subsequent filters and transformations.

Glob patterns are supported. Standard wildcards (globbing patterns) plus the ** doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | [] | +| include_srcs_packages | List of Bazel packages (with glob support) to include in output directory.

Files in srcs are only copied to the output directory if the Bazel package of the file matches one of the patterns specified.

Forward slashes (/) should be used as path separators. A first character of "." will be replaced by the target's package path.

Defaults to ["**"] which includes sources from all packages.

Files that have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Glob patterns are supported. Standard wildcards (globbing patterns) plus the ** doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | ["**"] | +| include_srcs_patterns | List of paths (with glob support) to include in output directory.

Files in srcs are only copied to the output directory if their output directory path, after applying root_paths, matches one of the patterns specified.

Forward slashes (/) should be used as path separators.

Defaults to ["**"] which includes all sources.

Files that have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be.

Glob patterns are supported. Standard wildcards (globbing patterns) plus the ** doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | ["**"] | | out | Path of the output directory, relative to this package.

If not set, the name of the target is used. | String | optional | "" | -| replace_prefixes | Map of paths prefixes (with glob support) to replace in the output directory path when copying files.

Glob patterns **, * and ? are supported but the pattern must not end with a ** glob expression. See glob_match documentation for more details on how to use glob patterns: https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md.

If the output directory path for a file or directory starts with or fully matches a a key in the dict then the matching portion of the output directory path is replaced with the dict value for that key. The final path segment matched can be a partial match of that segment and only the matching portion will be replaced. If there are multiple keys that match, the longest match wins.

Patterns do not look into files within source directory or generated directory (TreeArtifact) targets since matches are performed in Starlark. To use replace_prefixes on files within directories you can use the make_directory_paths helper to specify individual files inside directories in srcs. This restriction may be fixed in a future release by performing matching inside the copy action instead of in Starlark.

Forward slashes (/) should be used as path separators.

Replace prefix transformation are the final step in the list of filters and transformations. The final output path of a file or directory being copied into the output directory is determined at this step.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | Dictionary: String -> String | optional | {} | -| root_paths | List of paths (with glob support) that are roots in the output directory.

Glob patterns **, * and ? are supported. See glob_match documentation for more details on how to use glob patterns: https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md.

If any parent directory of a file or directory being copied matches one of the root paths patterns specified, the output directory path will be the path relative to the root path instead of the path relative to the file's or directory's workspace. If there are multiple root paths that match, the longest match wins.

Matching is done on the parent directory of the output file path so a trailing '**' glob patterm will match only up to the last path segment of the dirname and will not include the basename. Only complete path segments are matched. Partial matches on the last segment of the root path are ignored.

Forward slashes (/) should be used as path separators.

A "." value expands to the target's package path (ctx.label.package).

Defaults to ["."] which results in the output directory path of files in the target's package and and sub-packages are relative to the target's package and files outside of that retain their full workspace relative paths.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | ["."] | +| replace_prefixes | Map of paths prefixes (with glob support) to replace in the output directory path when copying files.

If the output directory path for a file starts with or fully matches a a key in the dict then the matching portion of the output directory path is replaced with the dict value for that key. The final path segment matched can be a partial match of that segment and only the matching portion will be replaced. If there are multiple keys that match, the longest match wins.

Forward slashes (/) should be used as path separators.

Replace prefix transformation are the final step in the list of filters and transformations. The final output path of a file being copied into the output directory is determined at this step.

Glob patterns are supported. Standard wildcards (globbing patterns) plus the ** doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | Dictionary: String -> String | optional | {} | +| root_paths | List of paths (with glob support) that are roots in the output directory.

If any parent directory of a file being copied matches one of the root paths patterns specified, the output directory path will be the path relative to the root path instead of the path relative to the file's workspace. If there are multiple root paths that match, the longest match wins.

Matching is done on the parent directory of the output file path so a trailing '**' glob patterm will match only up to the last path segment of the dirname and will not include the basename. Only complete path segments are matched. Partial matches on the last segment of the root path are ignored.

Forward slashes (/) should be used as path separators.

A "." value expands to the target's package path (ctx.label.package).

Defaults to ["."] which results in the output directory path of files in the target's package and and sub-packages are relative to the target's package and files outside of that retain their full workspace relative paths.

Glob patterns are supported. Standard wildcards (globbing patterns) plus the ** doublestar (aka. super-asterisk) are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns for more information on supported globbing patterns.

Filters and transformations are applied in the following order:

1. include_external_repositories

2. include_srcs_packages

3. exclude_srcs_packages

4. root_paths

5. include_srcs_patterns

6. exclude_srcs_patterns

7. replace_prefixes

For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. | List of strings | optional | ["."] | | srcs | Files and/or directories or targets that provide DirectoryPathInfo to copy into the output directory. | List of labels | optional | [] | +| verbose | If true, prints out verbose logs to stdout | Boolean | optional | False | @@ -48,7 +49,13 @@ copy_to_directory_action(ctx, replace_prefixes, allow_overwrites, is_windows) -Helper function to copy files to a directory. +Legacy helper function to copy files to a directory. + +This helper calculates copy paths in Starlark during analysis and performs the copies in a +bash/bat script. For improved analysis and runtime performance, it is recommended the switch +to `copy_to_directory_bin_action` which calculates copy paths and performs copies with a tool +binary, typically the `@aspect_bazel_lib//tools/copy_to_directory` `go_binary` either built +from source or provided by a toolchain. This helper is used by copy_to_directory. It is exposed as a public API so it can be used within other rule implementations where additional_files can also be passed in. @@ -75,6 +82,49 @@ other rule implementations where additional_files can also be passed in. | is_windows | Deprecated and unused | None | + + +## copy_to_directory_bin_action + +
+copy_to_directory_bin_action(ctx, name, dst, copy_to_directory_bin, files, targets, root_paths,
+                             include_external_repositories, include_srcs_packages,
+                             exclude_srcs_packages, include_srcs_patterns, exclude_srcs_patterns,
+                             exclude_prefixes, replace_prefixes, allow_overwrites, verbose)
+
+ +Helper function to copy files to a directory using a tool binary. + +The tool binary will typically be the `@aspect_bazel_lib//tools/copy_to_directory` `go_binary` +either built from source or provided by a toolchain. + +This helper is used by copy_to_directory. It is exposed as a public API so it can be used within +other rule implementations where additional_files can also be passed in. + + +**PARAMETERS** + + +| Name | Description | Default Value | +| :------------- | :------------- | :------------- | +| ctx | The rule context. | none | +| name | Name of target creating this action used for config file generation. | none | +| dst | The directory to copy to. Must be a TreeArtifact. | none | +| copy_to_directory_bin | Copy to directory tool binary. | none | +| files | List of files to copy into the output directory. | [] | +| targets | List of targets that provide DirectoryPathInfo to copy into the output directory. | [] | +| root_paths | List of paths that are roots in the output directory.

See copy_to_directory rule documentation for more details. | ["."] | +| include_external_repositories | List of external repository names to include in the output directory.

See copy_to_directory rule documentation for more details. | [] | +| include_srcs_packages | List of Bazel packages to include in output directory.

See copy_to_directory rule documentation for more details. | ["**"] | +| exclude_srcs_packages | List of Bazel packages (with glob support) to exclude from output directory.

See copy_to_directory rule documentation for more details. | [] | +| include_srcs_patterns | List of paths (with glob support) to include in output directory.

See copy_to_directory rule documentation for more details. | ["**"] | +| exclude_srcs_patterns | List of paths (with glob support) to exclude from output directory.

See copy_to_directory rule documentation for more details. | [] | +| exclude_prefixes | List of path prefixes to exclude from output directory.

See copy_to_directory rule documentation for more details. | [] | +| replace_prefixes | Map of paths prefixes to replace in the output directory path when copying files.

See copy_to_directory rule documentation for more details. | {} | +| allow_overwrites | If True, allow files to be overwritten if the same output file is copied to twice.

See copy_to_directory rule documentation for more details. | False | +| verbose | If true, prints out verbose logs to stdout | False | + + ## copy_to_directory_lib.impl diff --git a/e2e/copy_to_directory/BUILD.bazel b/e2e/copy_to_directory/BUILD.bazel index 7657522..95eb919 100644 --- a/e2e/copy_to_directory/BUILD.bazel +++ b/e2e/copy_to_directory/BUILD.bazel @@ -1,7 +1,7 @@ load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory") load("@aspect_bazel_lib//lib:diff_test.bzl", "diff_test") -# Test special cases of using "." and "./**" patterns in the root package +# Test special cases of using "./**" and "./*/**" patterns in the root package copy_to_directory( name = "dir1", @@ -10,7 +10,6 @@ copy_to_directory( "//subpkg:b", ], include_srcs_packages = [ - ".", "./**", ], ) @@ -57,7 +56,7 @@ copy_to_directory( "//subpkg:b", ], exclude_srcs_packages = [ - "./**", + "./*/**", ], ) @@ -84,7 +83,7 @@ copy_to_directory( "//subpkg:b", ], include_srcs_packages = [ - "./**", + "./*/**", ], ) diff --git a/lib/BUILD.bazel b/lib/BUILD.bazel index 9a9023d..2e88e2c 100644 --- a/lib/BUILD.bazel +++ b/lib/BUILD.bazel @@ -23,6 +23,10 @@ toolchain_type( name = "yq_toolchain_type", ) +toolchain_type( + name = "copy_to_directory_toolchain_type", +) + bzl_library( name = "docs", srcs = ["docs.bzl"], @@ -182,6 +186,7 @@ bzl_library( srcs = ["repositories.bzl"], deps = [ ":utils", + "//lib/private/docs:copy_to_directory_toolchain", "//lib/private/docs:jq_toolchain", "//lib/private/docs:local_config_platform", "//lib/private/docs:yq_toolchain", diff --git a/lib/copy_to_directory.bzl b/lib/copy_to_directory.bzl index f7a49cf..19fee97 100644 --- a/lib/copy_to_directory.bzl +++ b/lib/copy_to_directory.bzl @@ -7,19 +7,18 @@ the `root_paths`, `include_srcs_patters`, `exclude_srcs_patters` and `replace_pr load( "//lib/private:copy_to_directory.bzl", _copy_to_directory_action = "copy_to_directory_action", - # TODO: export copy_to_directory_bin_action once ready - # _copy_to_directory_bin_action = "copy_to_directory_bin_action", + _copy_to_directory_bin_action = "copy_to_directory_bin_action", _copy_to_directory_lib = "copy_to_directory_lib", ) # export the starlark library as a public API copy_to_directory_lib = _copy_to_directory_lib copy_to_directory_action = _copy_to_directory_action -# TODO: export copy_to_directory_bin_action once ready -# copy_to_directory_bin_action = _copy_to_directory_bin_action +copy_to_directory_bin_action = _copy_to_directory_bin_action copy_to_directory = rule( implementation = _copy_to_directory_lib.impl, provides = _copy_to_directory_lib.provides, attrs = _copy_to_directory_lib.attrs, + toolchains = ["@aspect_bazel_lib//lib:copy_to_directory_toolchain_type"], ) diff --git a/lib/extensions.bzl b/lib/extensions.bzl index a4e0d85..93d934e 100644 --- a/lib/extensions.bzl +++ b/lib/extensions.bzl @@ -2,6 +2,7 @@ load( "@aspect_bazel_lib//lib:repositories.bzl", + "register_copy_to_directory_toolchains", "register_jq_toolchains", "register_yq_toolchains", ) @@ -9,6 +10,7 @@ load( def _toolchain_extension(_): register_yq_toolchains(register = False) register_jq_toolchains(register = False) + register_copy_to_directory_toolchains(register = False) # TODO: some way for users to control repo name/version of the tools installed ext = module_extension( diff --git a/lib/private/copy_to_directory.bzl b/lib/private/copy_to_directory.bzl index 4b872c4..cabb3f3 100644 --- a/lib/private/copy_to_directory.bzl +++ b/lib/private/copy_to_directory.bzl @@ -27,6 +27,12 @@ For more information each filters / transformations applied, see the documentation for the specific filter / transformation attribute. """ +_glob_support_docstring = """Glob patterns are supported. Standard wildcards (globbing patterns) plus the `**` doublestar (aka. super-asterisk) +are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same +globbing library used by [gazelle](https://github.com/bazelbuild/bazel-gazelle). See https://github.com/bmatcuk/doublestar#patterns +for more information on supported globbing patterns. +""" + _copy_to_directory_attr = { "srcs": attr.label_list( allow_files = True, @@ -45,13 +51,9 @@ _copy_to_directory_attr = { default = ["."], doc = """List of paths (with glob support) that are roots in the output directory. - Glob patterns `**`, `*` and `?` are supported. See `glob_match` documentation for - more details on how to use glob patterns: - https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md. - - If any parent directory of a file or directory being copied matches one of the root paths + If any parent directory of a file being copied matches one of the root paths patterns specified, the output directory path will be the path relative to the root path - instead of the path relative to the file's or directory's workspace. If there are multiple + instead of the path relative to the file's workspace. If there are multiple root paths that match, the longest match wins. Matching is done on the parent directory of the output file path so a trailing '**' glob patterm @@ -67,16 +69,17 @@ _copy_to_directory_attr = { target's package and and sub-packages are relative to the target's package and files outside of that retain their full workspace relative paths. + {glob_support_docstring} + {filters_transform_order_docstring} - """.format(filters_transform_order_docstring = _filter_transforms_order_docstring), + """.format( + filters_transform_order_docstring = _filter_transforms_order_docstring, + glob_support_docstring = _glob_support_docstring, + ), ), "include_external_repositories": attr.string_list( doc = """List of external repository names (with glob support) to include in the output directory. - Glob patterns `**`, `*` and `?` are supported. See `glob_match` documentation for - more details on how to use glob patterns: - https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md. - Files from external repositories are only copied into the output directory if the external repository they come from matches one of the external repository patterns specified. @@ -96,182 +99,153 @@ _copy_to_directory_attr = { ) ``` - Files and directories that come from matching external are subject to subsequent filters and + Files that come from matching external are subject to subsequent filters and transformations to determine if they are copied and what their path in the output - directory will be. The external repository name of the file or directory from an external + directory will be. The external repository name of the file from an external repository is not included in the output directory path and is considered in subsequent filters and transformations. + {glob_support_docstring} + {filters_transform_order_docstring} - """.format(filters_transform_order_docstring = _filter_transforms_order_docstring), + """.format( + filters_transform_order_docstring = _filter_transforms_order_docstring, + glob_support_docstring = _glob_support_docstring, + ), ), "include_srcs_packages": attr.string_list( default = ["**"], doc = """List of Bazel packages (with glob support) to include in output directory. - Glob patterns `**`, `*` and `?` are supported. See `glob_match` documentation for - more details on how to use glob patterns: - https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md. + Files in srcs are only copied to the output directory if + the Bazel package of the file matches one of the patterns specified. - Files and directories in srcs are only copied to the output directory if - the Bazel package of the file or directory matches one of the patterns specified. - - Forward slashes (`/`) should be used as path separators. - - A `"."` value means include srcs that are in the target's package. - It expands to the target's package path (`ctx.label.package`). This - will be an empty string `""` if the target is in the root package. - - A `"./**"` value means include srcs that are in subpackages of the target's package. - It expands to the target's package path followed by a slash and a - globstar (`"{{}}/**".format(ctx.label.package)`). If the target's package is - the root package, `"./**"` expands to `["?*", "?*/**"]` instead. + Forward slashes (`/`) should be used as path separators. A first character of `"."` + will be replaced by the target's package path. Defaults to `["**"]` which includes sources from all packages. - Files and directories that have matching Bazel packages are subject to subsequent filters and + Files that have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. + {glob_support_docstring} + {filters_transform_order_docstring} - """.format(filters_transform_order_docstring = _filter_transforms_order_docstring), + """.format( + filters_transform_order_docstring = _filter_transforms_order_docstring, + glob_support_docstring = _glob_support_docstring, + ), ), "exclude_srcs_packages": attr.string_list( doc = """List of Bazel packages (with glob support) to exclude from output directory. - Glob patterns `**`, `*` and `?` are supported. See `glob_match` documentation for - more details on how to use glob patterns: - https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md. + Files in srcs are not copied to the output directory if + the Bazel package of the file matches one of the patterns specified. - Files and directories in srcs are not copied to the output directory if - the Bazel package of the file or directory matches one of the patterns specified. + Forward slashes (`/`) should be used as path separators. A first character of `"."` + will be replaced by the target's package path. - Forward slashes (`/`) should be used as path separators. - - A `"."` value means exclude srcs that are in the target's package. - It expands to the target's package path (`ctx.label.package`). This - will be an empty string `""` if the target is in the root package. - - A `"./**"` value means exclude srcs that are in subpackages of the target's package. - It expands to the target's package path followed by a slash and a - globstar (`"{{}}/**".format(ctx.label.package)`). If the target's package is - the root package, `"./**"` expands to `["?*", "?*/**"]` instead. - - Files and directories that have do not have matching Bazel packages are subject to subsequent + Files that have do not have matching Bazel packages are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. + {glob_support_docstring} + {filters_transform_order_docstring} - """.format(filters_transform_order_docstring = _filter_transforms_order_docstring), + """.format( + filters_transform_order_docstring = _filter_transforms_order_docstring, + glob_support_docstring = _glob_support_docstring, + ), ), "include_srcs_patterns": attr.string_list( default = ["**"], doc = """List of paths (with glob support) to include in output directory. - Glob patterns `**`, `*` and `?` are supported. See `glob_match` documentation for - more details on how to use glob patterns: - https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md. - - Files and directories in srcs are only copied to the output directory if their output + Files in srcs are only copied to the output directory if their output directory path, after applying `root_paths`, matches one of the patterns specified. - Patterns do not look into files within source directory or generated directory (TreeArtifact) - targets since matches are performed in Starlark. To use `include_srcs_patterns` on files - within directories you can use the `make_directory_paths` helper to specify individual files inside - directories in `srcs`. This restriction may be fixed in a future release by performing matching - inside the copy action instead of in Starlark. - Forward slashes (`/`) should be used as path separators. Defaults to ["**"] which includes all sources. - Files and directories that have matching output directory paths are subject to subsequent + Files that have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. + {glob_support_docstring} + {filters_transform_order_docstring} - """.format(filters_transform_order_docstring = _filter_transforms_order_docstring), + """.format( + filters_transform_order_docstring = _filter_transforms_order_docstring, + glob_support_docstring = _glob_support_docstring, + ), ), "exclude_srcs_patterns": attr.string_list( doc = """List of paths (with glob support) to exclude from output directory. - Glob patterns `**`, `*` and `?` are supported. See `glob_match` documentation for - more details on how to use glob patterns: - https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md. - - Files and directories in srcs are not copied to the output directory if their output + Files in srcs are not copied to the output directory if their output directory path, after applying `root_paths`, matches one of the patterns specified. - Patterns do not look into files within source directory or generated directory (TreeArtifact) - targets since matches are performed in Starlark. To use `include_srcs_patterns` on files - within directories you can use the `make_directory_paths` helper to specify individual files inside - directories in `srcs`. This restriction may be fixed in a future release by performing matching - inside the copy action instead of in Starlark. - Forward slashes (`/`) should be used as path separators. - Files and directories that do not have matching output directory paths are subject to subsequent + Files that do not have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. + {glob_support_docstring} + {filters_transform_order_docstring} - """.format(filters_transform_order_docstring = _filter_transforms_order_docstring), + """.format( + filters_transform_order_docstring = _filter_transforms_order_docstring, + glob_support_docstring = _glob_support_docstring, + ), ), "exclude_prefixes": attr.string_list( doc = """List of path prefixes (with glob support) to exclude from output directory. DEPRECATED: use `exclude_srcs_patterns` instead - Glob patterns `**`, `*` and `?` are supported. See `glob_match` documentation for - more details on how to use glob patterns: - https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md. - - Files and directories in srcs are not copied to the output directory if their output + Files in srcs are not copied to the output directory if their output directory path, after applying `root_paths`, starts with or fully matches one of the patterns specified. - Patterns do not look into files within source directory or generated directory (TreeArtifact) - targets since matches are performed in Starlark. To use `include_srcs_patterns` on files - within directories you can use the `make_directory_paths` helper to specify individual files inside - directories in `srcs`. This restriction may be fixed in a future release by performing matching - inside the copy action instead of in Starlark. - Forward slashes (`/`) should be used as path separators. - Files and directories that do not have matching output directory paths are subject to subsequent + Files that do not have matching output directory paths are subject to subsequent filters and transformations to determine if they are copied and what their path in the output directory will be. + {glob_support_docstring} + {filters_transform_order_docstring} - """.format(filters_transform_order_docstring = _filter_transforms_order_docstring), + """.format( + filters_transform_order_docstring = _filter_transforms_order_docstring, + glob_support_docstring = _glob_support_docstring, + ), ), "replace_prefixes": attr.string_dict( doc = """Map of paths prefixes (with glob support) to replace in the output directory path when copying files. - Glob patterns `**`, `*` and `?` are supported but the pattern must not end with a `**` glob - expression. See `glob_match` documentation for more details on how to use glob patterns: - https://github.com/aspect-build/bazel-lib/blob/main/docs/glob_match.md. - - If the output directory path for a file or directory starts with or fully matches a + If the output directory path for a file starts with or fully matches a a key in the dict then the matching portion of the output directory path is replaced with the dict value for that key. The final path segment matched can be a partial match of that segment and only the matching portion will be replaced. If there are multiple keys that match, the longest match wins. - Patterns do not look into files within source directory or generated directory (TreeArtifact) - targets since matches are performed in Starlark. To use `replace_prefixes` on files - within directories you can use the `make_directory_paths` helper to specify individual files inside - directories in `srcs`. This restriction may be fixed in a future release by performing matching - inside the copy action instead of in Starlark. - Forward slashes (`/`) should be used as path separators. Replace prefix transformation are the final step in the list of filters and transformations. - The final output path of a file or directory being copied into the output directory + The final output path of a file being copied into the output directory is determined at this step. + {glob_support_docstring} + {filters_transform_order_docstring} - """.format(filters_transform_order_docstring = _filter_transforms_order_docstring), + """.format( + filters_transform_order_docstring = _filter_transforms_order_docstring, + glob_support_docstring = _glob_support_docstring, + ), ), "allow_overwrites": attr.bool( doc = """If True, allow files to be overwritten if the same output file is copied to twice. @@ -280,10 +254,11 @@ _copy_to_directory_attr = { This setting has no effect on Windows where overwrites are always allowed.""", ), - # TODO: flip to copy_to_directory_bin_action once ready - # "verbose": attr.bool( - # doc = """If true, prints out verbose logs to stdout""", - # ), + "verbose": attr.bool( + doc = """If true, prints out verbose logs to stdout""", + ), + # use '_tool' attribute for development only; do not commit with this attribute active since it + # propagates a dependency on rules_go which would be breaking for users # "_tool": attr.label( # executable = True, # cfg = "exec", @@ -597,12 +572,17 @@ if exist "{src}\\*" ( ) def _copy_to_directory_impl(ctx): + copy_to_directory_bin = ctx.toolchains["@aspect_bazel_lib//lib:copy_to_directory_toolchain_type"].copy_to_directory_info.bin + dst = ctx.actions.declare_directory(ctx.attr.out if ctx.attr.out else ctx.attr.name) - copy_to_directory_action( + copy_to_directory_bin_action( ctx, - srcs = ctx.attr.srcs, + name = ctx.attr.name, dst = dst, + copy_to_directory_bin = copy_to_directory_bin, # use ctx.executable._tool for development + files = ctx.files.srcs, + targets = [t for t in ctx.attr.srcs if DirectoryPathInfo in t], root_paths = ctx.attr.root_paths, include_external_repositories = ctx.attr.include_external_repositories, include_srcs_packages = ctx.attr.include_srcs_packages, @@ -612,28 +592,9 @@ def _copy_to_directory_impl(ctx): exclude_prefixes = ctx.attr.exclude_prefixes, replace_prefixes = ctx.attr.replace_prefixes, allow_overwrites = ctx.attr.allow_overwrites, + verbose = ctx.attr.verbose, ) - # TODO: flip to copy_to_directory_bin_action once ready - # copy_to_directory_bin_action( - # ctx, - # name = ctx.attr.name, - # dst = dst, - # copy_to_directory_bin = ctx.executable._tool, - # files = ctx.files.srcs, - # targets = [t for t in ctx.attr.srcs if DirectoryPathInfo in t], - # root_paths = ctx.attr.root_paths, - # include_external_repositories = ctx.attr.include_external_repositories, - # include_srcs_packages = ctx.attr.include_srcs_packages, - # exclude_srcs_packages = ctx.attr.exclude_srcs_packages, - # include_srcs_patterns = ctx.attr.include_srcs_patterns, - # exclude_srcs_patterns = ctx.attr.exclude_srcs_patterns, - # exclude_prefixes = ctx.attr.exclude_prefixes, - # replace_prefixes = ctx.attr.replace_prefixes, - # allow_overwrites = ctx.attr.allow_overwrites, - # verbose = ctx.attr.verbose, - # ) - return [ DefaultInfo( files = depset([dst]), @@ -644,15 +605,12 @@ def _copy_to_directory_impl(ctx): def _expand_src_packages_patterns(patterns, package): result = [] for pattern in patterns: - if pattern == ".": - result.append(package) - elif pattern == "./**": - if package: - result.append("{}/**".format(package)) + if pattern.startswith("."): + if not package and pattern.startswith("./"): + # special case in the root package + result.append(pattern[2:]) else: - # special case for the root package so we match on subpackages but - # not on the empty root package itself - result.extend(["?*", "?*/**"]) + result.append(package + pattern[1:]) else: result.append(pattern) return result @@ -737,7 +695,7 @@ def copy_to_directory_bin_action( # Replace "." in root_paths with the package name of the target root_paths = [p if p != "." else ctx.label.package for p in root_paths] - # Replace "." and "./**" patterns in in include_srcs_packages & exclude_srcs_packages + # Replace a leading "." with the package name of the target in include_srcs_packages & exclude_srcs_packages include_srcs_packages = _expand_src_packages_patterns(include_srcs_packages, ctx.label.package) exclude_srcs_packages = _expand_src_packages_patterns(exclude_srcs_packages, ctx.label.package) @@ -850,6 +808,7 @@ def copy_to_directory_bin_action( execution_requirements = _COPY_EXECUTION_REQUIREMENTS, ) +# TODO(2.0): remove the legacy copy_to_directory_action helper def copy_to_directory_action( ctx, srcs, @@ -865,7 +824,13 @@ def copy_to_directory_action( replace_prefixes = {}, allow_overwrites = False, is_windows = None): - """Helper function to copy files to a directory. + """Legacy helper function to copy files to a directory. + + This helper calculates copy paths in Starlark during analysis and performs the copies in a + bash/bat script. For improved analysis and runtime performance, it is recommended the switch + to `copy_to_directory_bin_action` which calculates copy paths and performs copies with a tool + binary, typically the `@aspect_bazel_lib//tools/copy_to_directory` `go_binary` either built + from source or provided by a toolchain. This helper is used by copy_to_directory. It is exposed as a public API so it can be used within other rule implementations where additional_files can also be passed in. @@ -925,7 +890,7 @@ def copy_to_directory_action( # Replace "." in root_paths with the package name of the target root_paths = [p if p != "." else ctx.label.package for p in root_paths] - # Replace "." and "./**" patterns in in include_srcs_packages & exclude_srcs_packages + # Replace a leading "." with the package name of the target in include_srcs_packages & exclude_srcs_packages include_srcs_packages = _expand_src_packages_patterns(include_srcs_packages, ctx.label.package) exclude_srcs_packages = _expand_src_packages_patterns(exclude_srcs_packages, ctx.label.package) diff --git a/lib/private/copy_to_directory_toolchain.bzl b/lib/private/copy_to_directory_toolchain.bzl new file mode 100644 index 0000000..d2fc135 --- /dev/null +++ b/lib/private/copy_to_directory_toolchain.bzl @@ -0,0 +1,188 @@ +"Setup copy_to_directory toolchain repositories and rules" + +# Platform names follow the platform naming convention in @aspect_bazel_lib//:lib/private/repo_utils.bzl +COPY_TO_DIRECTORY_PLATFORMS = { + "darwin_amd64": struct( + compatible_with = [ + "@platforms//os:macos", + "@platforms//cpu:x86_64", + ], + ), + "darwin_arm64": struct( + compatible_with = [ + "@platforms//os:macos", + "@platforms//cpu:aarch64", + ], + ), + "linux_amd64": struct( + compatible_with = [ + "@platforms//os:linux", + "@platforms//cpu:x86_64", + ], + ), + "linux_arm64": struct( + compatible_with = [ + "@platforms//os:linux", + "@platforms//cpu:aarch64", + ], + ), + "windows_amd64": struct( + compatible_with = [ + "@platforms//os:windows", + "@platforms//cpu:x86_64", + ], + ), +} + +# https://github.com/aspect-build/bazel-lib/releases +# +# The integrity hashes can be automatically fetched for the latest copy_to_directory release by running +# `tools/copy_to_directory_mirror_release.sh`. To calculate for a specific release run +# `tools/copy_to_directory_mirror_release.sh ` + +COPY_TO_DIRECTORY_VERSION = "1.19.2" +COPY_TO_DIRECTORY_INTEGRITY = { + "darwin_amd64": "sha256-TdU9sae6uxjkABWnIh5DhHr52KuNPy/F3Lo5MH/hbWc=", + "darwin_arm64": "sha256-jLM7ZWI1xqp1tHcOf8MdQOurgLlAhppvhr1zSsBwOqA=", + "linux_amd64": "sha256-38Plushs6HNUemnAGRS7nN1Bc9Fq5z209m9OOGVCrm4=", + "linux_arm64": "sha256-TbyibQbo2QORCBpX08e4YLDPbFsCQNyk1jxePwe1cFI=", + "windows_amd64": "sha256-0xgHiwX0qHi2TGn1v+cBK7rHTgaz2ulYxCnvF07cVh4=", +} + +CopyToDirectoryInfo = provider( + doc = "Provide info for executing copy_to_directory", + fields = { + "bin": "Executable copy_to_directory binary", + }, +) + +def _copy_to_directory_toolchain_impl(ctx): + binary = ctx.attr.bin.files.to_list()[0] + + default_info = DefaultInfo( + files = depset([binary]), + runfiles = ctx.runfiles(files = [binary]), + ) + copy_to_directory_info = CopyToDirectoryInfo( + bin = binary, + ) + + # Export all the providers inside our ToolchainInfo + # so the resolved_toolchain rule can grab and re-export them. + toolchain_info = platform_common.ToolchainInfo( + copy_to_directory_info = copy_to_directory_info, + default = default_info, + ) + + return [default_info, toolchain_info] + +copy_to_directory_toolchain = rule( + implementation = _copy_to_directory_toolchain_impl, + attrs = { + "bin": attr.label( + mandatory = True, + allow_single_file = True, + executable = True, + cfg = "exec", + ), + }, +) + +def _copy_to_directory_toolchains_repo_impl(rctx): + # Expose a concrete toolchain which is the result of Bazel resolving the toolchain + # for the execution or target platform. + # Workaround for https://github.com/bazelbuild/bazel/issues/14009 + starlark_content = """# @generated by @aspect_bazel_lib//lib/private:copy_to_directory_toolchain.bzl + +# Forward all the providers +def _resolved_toolchain_impl(ctx): + toolchain_info = ctx.toolchains["@aspect_bazel_lib//lib:copy_to_directory_toolchain_type"] + return [ + toolchain_info, + toolchain_info.default, + toolchain_info.copy_to_directory_info, + toolchain_info.template_variables, + ] + +# Copied from java_toolchain_alias +# https://cs.opensource.google/bazel/bazel/+/master:tools/jdk/java_toolchain_alias.bzl +resolved_toolchain = rule( + implementation = _resolved_toolchain_impl, + toolchains = ["@aspect_bazel_lib//lib:copy_to_directory_toolchain_type"], + incompatible_use_toolchain_transition = True, +) +""" + rctx.file("defs.bzl", starlark_content) + + build_content = """# @generated by @aspect_bazel_lib//lib/private:copy_to_directory_toolchain.bzl +# +# These can be registered in the workspace file or passed to --extra_toolchains flag. +# By default all these toolchains are registered by the copy_to_directory_register_toolchains macro +# so you don't normally need to interact with these targets. + +load(":defs.bzl", "resolved_toolchain") + +resolved_toolchain(name = "resolved_toolchain", visibility = ["//visibility:public"]) + +""" + + for [platform, meta] in COPY_TO_DIRECTORY_PLATFORMS.items(): + build_content += """ +toolchain( + name = "{platform}_toolchain", + exec_compatible_with = {compatible_with}, + toolchain = "@{user_repository_name}_{platform}//:copy_to_directory_toolchain", + toolchain_type = "@aspect_bazel_lib//lib:copy_to_directory_toolchain_type", +) +""".format( + platform = platform, + user_repository_name = rctx.attr.user_repository_name, + compatible_with = meta.compatible_with, + ) + + # Base BUILD file for this repository + rctx.file("BUILD.bazel", build_content) + +copy_to_directory_toolchains_repo = repository_rule( + _copy_to_directory_toolchains_repo_impl, + doc = """Creates a repository with toolchain definitions for all known platforms + which can be registered or selected.""", + attrs = { + "user_repository_name": attr.string(doc = "Base name for toolchains repository"), + }, +) + +def _copy_to_directory_platform_repo_impl(rctx): + is_windows = rctx.attr.platform.startswith("windows_") + meta = COPY_TO_DIRECTORY_PLATFORMS[rctx.attr.platform] + release_platform = meta.release_platform if hasattr(meta, "release_platform") else rctx.attr.platform + + # https://github.com/aspect-build/bazel-lib/releases/download/v1.19.0/copy_to_directory-linux_amd64 + url = "https://github.com/aspect-build/bazel-lib/releases/download/v{0}/copy_to_directory-{1}{2}".format( + COPY_TO_DIRECTORY_VERSION, + release_platform, + ".exe" if is_windows else "", + ) + + rctx.download( + url = url, + output = "copy_to_directory.exe" if is_windows else "copy_to_directory", + executable = True, + integrity = COPY_TO_DIRECTORY_INTEGRITY[release_platform], + ) + build_content = """# @generated by @aspect_bazel_lib//lib/private:copy_to_directory_toolchain.bzl +load("@aspect_bazel_lib//lib/private:copy_to_directory_toolchain.bzl", "copy_to_directory_toolchain") +exports_files(["{0}"]) +copy_to_directory_toolchain(name = "copy_to_directory_toolchain", bin = "{0}", visibility = ["//visibility:public"]) +""".format("copy_to_directory.exe" if is_windows else "copy_to_directory") + + # Base BUILD file for this repository + rctx.file("BUILD.bazel", build_content) + +copy_to_directory_platform_repo = repository_rule( + implementation = _copy_to_directory_platform_repo_impl, + doc = "Fetch external tools needed for copy_to_directory toolchain", + attrs = { + "platform": attr.string(mandatory = True, values = COPY_TO_DIRECTORY_PLATFORMS.keys()), + }, +) diff --git a/lib/private/docs/BUILD.bazel b/lib/private/docs/BUILD.bazel index 516303c..a91d858 100644 --- a/lib/private/docs/BUILD.bazel +++ b/lib/private/docs/BUILD.bazel @@ -227,3 +227,8 @@ bzl_library( name = "base64", srcs = ["//lib/private:base64.bzl"], ) + +bzl_library( + name = "copy_to_directory_toolchain", + srcs = ["//lib/private:copy_to_directory_toolchain.bzl"], +) diff --git a/lib/repositories.bzl b/lib/repositories.bzl index 7dd79bd..ed7ff59 100644 --- a/lib/repositories.bzl +++ b/lib/repositories.bzl @@ -2,9 +2,11 @@ load("//lib/private:jq_toolchain.bzl", "JQ_PLATFORMS", "jq_host_alias_repo", "jq_platform_repo", "jq_toolchains_repo", _DEFAULT_JQ_VERSION = "DEFAULT_JQ_VERSION") load("//lib/private:yq_toolchain.bzl", "YQ_PLATFORMS", "yq_host_alias_repo", "yq_platform_repo", "yq_toolchains_repo", _DEFAULT_YQ_VERSION = "DEFAULT_YQ_VERSION") +load("//lib/private:copy_to_directory_toolchain.bzl", "COPY_TO_DIRECTORY_PLATFORMS", "copy_to_directory_platform_repo", "copy_to_directory_toolchains_repo") load("//lib/private:local_config_platform.bzl", "local_config_platform") load("//lib:utils.bzl", "is_bazel_6_or_greater", http_archive = "maybe_http_archive") +# buildifier: disable=unnamed-macro def aspect_bazel_lib_dependencies(override_local_config_platform = False): """Load dependencies required by aspect rules @@ -31,6 +33,9 @@ def aspect_bazel_lib_dependencies(override_local_config_platform = False): name = "local_config_platform", ) + # Always register the copy_to_directory toolchain + register_copy_to_directory_toolchains() + # Re-export the default versions DEFAULT_JQ_VERSION = _DEFAULT_JQ_VERSION DEFAULT_YQ_VERSION = _DEFAULT_YQ_VERSION @@ -84,3 +89,24 @@ def register_yq_toolchains(name = "yq", version = DEFAULT_YQ_VERSION, register = name = "%s_toolchains" % name, user_repository_name = name, ) + +def register_copy_to_directory_toolchains(name = "copy_to_directory", register = True): + """Registers copy_to_directory toolchain and repositories + + Args: + name: override the prefix for the generated toolchain repositories + register: whether to call through to native.register_toolchains. + Should be True for WORKSPACE users, but false when used under bzlmod extension + """ + for [platform, meta] in COPY_TO_DIRECTORY_PLATFORMS.items(): + copy_to_directory_platform_repo( + name = "%s_%s" % (name, platform), + platform = platform, + ) + if register: + native.register_toolchains("@%s_toolchains//:%s_toolchain" % (name, platform)) + + copy_to_directory_toolchains_repo( + name = "%s_toolchains" % name, + user_repository_name = name, + ) diff --git a/lib/tests/copy_to_directory/BUILD.bazel b/lib/tests/copy_to_directory/BUILD.bazel index 66c289d..857ec89 100644 --- a/lib/tests/copy_to_directory/BUILD.bazel +++ b/lib/tests/copy_to_directory/BUILD.bazel @@ -82,9 +82,6 @@ copy_to_directory( # flatten test_a & test_b to the root "test_a": "", "test_b": "", - # some paths that won't match - "a/": "wont_match_a_is_terminal_path", - "a/a2": "wont_match_since_a2_is_in_a_tree_artifact", }, ) @@ -100,6 +97,7 @@ copy_to_directory( srcs = case_srcs, include_external_repositories = ["external_test_repo"], root_paths = [], + verbose = True, ) diff_test( @@ -178,12 +176,18 @@ copy_to_directory( name = "case_8", srcs = case_srcs, exclude_srcs_patterns = [ - "a", - "b", + "a/*", + "b/*", "e/e*", ], ) +diff_test( + name = "case_8_test", + file1 = "case_8", + file2 = ":expected_8", +) + # Case 9: directory_path srcs & replace_prefixes (with external repo) copy_to_directory( name = "case_9", @@ -224,8 +228,6 @@ copy_to_directory( # flatten test_a & test_b to the root "test_a": "", "test_b": "", - # some paths that won't match - "a/a2": "wont_match_since_a2_is_not_included_in_the_directory_path_in_srcs", }, ) @@ -235,12 +237,6 @@ diff_test( file2 = ":expected_9", ) -diff_test( - name = "case_8_test", - file1 = "case_8", - file2 = ":expected_8", -) - # Case 10: copy folder containing hidden file copy_to_directory( name = "case_10", @@ -313,8 +309,8 @@ copy_to_directory( name = "case_13", srcs = case_srcs, include_srcs_patterns = [ - "a", - "b", + "a/*", + "b/*", "?/e*", "f/f2/f2", ], @@ -334,8 +330,8 @@ copy_to_directory( "f/f2/f1", ], include_srcs_patterns = [ - "a", - "b", + "a/*", + "b/*", "?/e*", "f/f?/**", ], @@ -395,7 +391,7 @@ diff_test( copy_to_directory( name = "case_18", srcs = case_srcs, - exclude_srcs_packages = ["./**"], + exclude_srcs_packages = ["./*/**"], include_external_repositories = ["e?ter*_test_repo"], ) @@ -405,12 +401,12 @@ diff_test( file2 = ":expected_18", ) -# Case 19: include_srcs_packages with "./**" expansion +# Case 19: include_srcs_packages with "./*/**" expansion copy_to_directory( name = "case_19", srcs = case_srcs, include_external_repositories = ["externa?_*_rep*"], - include_srcs_packages = ["./**"], + include_srcs_packages = ["./*/**"], ) diff_test( diff --git a/lib/tests/copy_to_directory_bin_action/BUILD.bazel b/lib/tests/copy_to_directory_bin_action/BUILD.bazel index 7aa0de9..e4bafab 100644 --- a/lib/tests/copy_to_directory_bin_action/BUILD.bazel +++ b/lib/tests/copy_to_directory_bin_action/BUILD.bazel @@ -18,7 +18,9 @@ copy_directory( lib( name = "lib", - srcs = ["1"], + srcs = [ + "1", + ], # intentionally dup on "1" to make sure it is gracefully handled others = [ "1", diff --git a/tools/copy_to_directory_mirror_release.sh b/tools/copy_to_directory_mirror_release.sh new file mode 100755 index 0000000..a48aeca --- /dev/null +++ b/tools/copy_to_directory_mirror_release.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Produce a dictionary for the current copy_to_directory tool release, +# suitable for adding to lib/private/copy_to_directory_toolchain.bzl + +set -o errexit -o nounset -o pipefail + +# Find the latest version +if [ "${1:-}" ]; then + version=$1 +else + version=$(curl --silent "https://api.github.com/repos/aspect-build/bazel-lib/releases/latest" | grep '"tag_name":' | sed -E 's/.*"v([^"]+)".*/\1/') +fi + +# Extract the checksums and output a starlark map entry +echo "COPY_TO_DIRECTORY_VERSION = \"$version\"" +echo "COPY_TO_DIRECTORY_INTEGRITY = {" +platforms=(darwin_{amd64,arm64} linux_{amd64,arm64} windows_amd64) +for release in ${platforms[@]}; do + integrity="https://github.com/aspect-build/bazel-lib/releases/download/v$version/copy_to_directory-$release" + if [[ $release == windows* ]]; then + integrity="$integrity.exe" + fi + integrity="$integrity.sha256" + curl --silent --location $integrity -o "/tmp/$release.sha256" + + echo " \"$release\": \"sha256-$(cat /tmp/$release.sha256 | awk '{ print $1 }' | xxd -r -p | base64)\"," +done +echo "}" + +printf "\n" +echo "Paste the above into lib/private/copy_to_directory_toolchain.bzl" \ No newline at end of file