Compiling Rocket in Bazel - rust

I'm attempting to get a working prototype of the following scenario:
Language: Rust (rustc 1.45.0-nightly (ad4bc3323 2020-06-01))
Framework: Rocket v0.4.4
Build Tool: Bazel
Platform: Mac OS X / Darwin x64
Running bazel build //web-api yields the below error. I believe, based on looking at the Cargo.lock file it is because Rocket's dependency on the hyper library specifies a dependency on the log 0.3.9 library. For whatever reason it is not using the more recent log=0.4.x. That said, I don't know why it's pulling this library since, if I build it manually, it works fine.
ERROR: /private/var/tmp/_bazel_nathanielford/2a39169ea9f6eb02fe788b12f9eae88f/external/raze__log__0_3_9/BUILD.bazel:27:1: error executing shell command: '/bin/bash -c CARGO_MANIFEST_DIR=$(pwd)/external/raze__log__0_3_9 external/rust_darwin_x86_64/bin/rustc "$#" --remap-path-prefix="$(pwd)"=__bazel_redacted_pwd external/raze__log__0_3_9/src/lib.rs -...' failed (Exit 1) bash failed: error executing command /bin/bash -c 'CARGO_MANIFEST_DIR=$(pwd)/external/raze__log__0_3_9 external/rust_darwin_x86_64/bin/rustc "$#" --remap-path-prefix="$(pwd)"=__bazel_redacted_pwd' '' external/raze__log__0_3_9/src/lib.rs ... (remaining 24 argument(s) skipped)
Use --sandbox_debug to see verbose messages from the sandbox
error[E0425]: cannot find function `set_logger` in crate `log`
--> external/raze__log__0_3_9/src/lib.rs:731:16
|
731 | match log::set_logger(&ADAPTOR) {
| ^^^^^^^^^^ not found in `log`
|
help: consider importing this function
|
204 | use set_logger;
|
The following is my directory structure:
/
|-WORKSPACE
|-BUILD # Empty
|-web-api/
| |-BUILD
| |-src/
| | |-main.rs
| |-cargo/
| |-Cargo.toml
| |-Cargo.lock
| |-BUILD.bazel
| |-remote/
| |-... (Cargo-raze files)
In order to set up the cargo-raze I did the following, following instructions from the github page.:
$ cd web-api/cargo
$ cargo generate-lockfile
$ cargo vendor --versioned-dirs --locked
$ cargo raze
(The generate-lockfile is what creates the Cargo.lock file, and the cargo raze is what creates the BUILD.bazel file and all the contents of the remote sub directory.)
And then to execute the bazel build I go back to the root and run bazel build //web-api, which produces the above error.
This is my WORKSPACE file:
workspace(name = "rocket-bazel")
load("#bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "io_bazel_rules_rust",
sha256 = "f21c67fc2fef9d57fa3c81fde1defd9e57d451883388c0a469ec1c470fd30dcb",
strip_prefix = "rules_rust-master",
urls = [
"https://github.com/bazelbuild/rules_rust/archive/master.tar.gz"
],
)
http_archive(
name = "bazel_skylib",
sha256 = "9a737999532daca978a158f94e77e9af6a6a169709c0cee274f0a4c3359519bd",
strip_prefix = "bazel-skylib-1.0.0",
url = "https://github.com/bazelbuild/bazel-skylib/archive/1.0.0.tar.gz",
)
load("#io_bazel_rules_rust//rust:repositories.bzl", "rust_repositories")
rust_repositories(version="nightly", iso_date="2020-06-02")
load("#io_bazel_rules_rust//:workspace.bzl", "bazel_version")
bazel_version(name = "bazel_version")
load("//web-api/cargo:crates.bzl", "raze_fetch_remote_crates")
raze_fetch_remote_crates()
This is my web-api/BUILD file:
load("#io_bazel_rules_rust//rust:rust.bzl", "rust_binary")
rust_binary(
name = "web-api",
srcs = ["src/main.rs"],
deps = [
"//web-api/cargo:rocket",
],
)
And my web-api/cargo/Cargo.toml file:
load("#io_bazel_rules_rust//rust:rust.bzl", "rust_binary")
rust_binary(
name = "web-api",
srcs = ["src/main.rs"],
deps = [
"//web-api/cargo:rocket",
],
)
I've run out of ideas as to what to try. I can get this to compile without Bazel, just using rust (though obviously the files are in slightly different places). I can get it to compile inside a Docker container. I just can't get Bazel (necessarily with cargo raze, either in vendor or remote mode) to run successfully: I assume that there is some mismatch in compile target or the nightly build that is not being properly set - but I'm not sure how to diagnose or get past that.
Here is a link to a repository with the files/structure I tried.

I had a similar issue when I made a minimal Bazel workspace with rust and the log crate together with env_logger crate. I found a similar issue when you try to compile without features = ["std"]. I then tried to enable that in Cargo.toml on the log dependency without success.
My solution is that in Cargo.toml under [raze] I added:
default_gen_buildrs = true
I could trace it down to that when default_gen_buildrs flag is not set in the generated log crate the BUILD.bazel file did not have a cargo_build_script definition or this:
crate_features = [
"std",
],

Related

Yocto bitbake core-image-sato with preempt-rt failed

I want to set up a linux kernel with preempt-RT with yocto.
According to meta/recipes-rt/README, I add the following code in build/conf/local.conf, and do bitbake core-image-sato, but bitbake fail.
MACHINE ?= "genericx86-64"
PREFERRED_PROVIDER_virtual/kernel = "linux-yocto-rt"
COMPATIBLE_MACHINE_genericx86-64 = "genericx86-64"
COMPATIBLE_MACHINE_quilt-native = "genericx86-64"
Yocto output the following error:
NOTE: Bitbake server didn't start within 5 seconds, waiting for 90
Loading cache: 100% |#######################################################################################################################################################################| Time: 0:00:13
Loaded 1330 entries from dependency cache.
NOTE: Resolving any missing task queue dependencies
Build Configuration:
BB_VERSION = "1.46.0"
BUILD_SYS = "x86_64-linux"
NATIVELSBSTRING = "universal"
TARGET_SYS = "x86_64-poky-linux"
MACHINE = "genericx86-64"
DISTRO = "poky"
DISTRO_VERSION = "3.1.20"
TUNE_FEATURES = "m64 core2"
TARGET_FPU = ""
meta
meta-poky
meta-yocto-bsp = "dunfell:90a6f6a110ab14890e2f6a1616e74ee259fc0f8f"
Initialising tasks: 100% |##################################################################################################################################################################| Time: 0:00:48
Sstate summary: Wanted 14 Found 0 Missed 14 Current 1203 (0% match, 98% complete)
NOTE: Executing Tasks
ERROR: linux-yocto-rt-5.4.213+gitAUTOINC+2f18e629f7_03cd66d981-r0 do_kernel_metadata: Could not locate BSP definition for genericx86-64/preempt-rt and no defconfig was provided
ERROR: linux-yocto-rt-5.4.213+gitAUTOINC+2f18e629f7_03cd66d981-r0 do_kernel_metadata: Execution of '/media/fff/disk1T/yocto/demo3/poky/build/tmp/work/genericx86_64-poky-linux/linux-yocto-rt/5.4.213+gitAUTOINC+2f18e629f7_03cd66d981-r0/temp/run.do_kernel_metadata.1138429' failed with exit code 1
ERROR: Logfile of failure stored in: /media/fff/disk1T/yocto/demo3/poky/build/tmp/work/genericx86_64-poky-linux/linux-yocto-rt/5.4.213+gitAUTOINC+2f18e629f7_03cd66d981-r0/temp/log.do_kernel_metadata.1138429
Log data follows:
| DEBUG: Executing python function extend_recipe_sysroot
| NOTE: Direct dependencies are ['/media/fff/disk1T/yocto/demo3/poky/meta/recipes-kernel/kern-tools/kern-tools-native_git.bb:do_populate_sysroot']
| NOTE: Installed into sysroot: []
| NOTE: Skipping as already exists in sysroot: ['kern-tools-native', 'quilt-native']
| DEBUG: Python function extend_recipe_sysroot finished
| DEBUG: Executing shell function do_kernel_metadata
| NOTE: do_kernel_metadata: for summary/debug, set KCONF_AUDIT_LEVEL > 0
| ERROR: Could not locate BSP definition for genericx86-64/preempt-rt and no defconfig was provided
| WARNING: exit code 1 from a shell command.
| ERROR: Execution of '/media/fff/disk1T/yocto/demo3/poky/build/tmp/work/genericx86_64-poky-linux/linux-yocto-rt/5.4.213+gitAUTOINC+2f18e629f7_03cd66d981-r0/temp/run.do_kernel_metadata.1138429' failed with exit code 1
ERROR: Task (/media/fff/disk1T/yocto/demo3/poky/meta/recipes-kernel/linux/linux-yocto-rt_5.4.bb:do_kernel_metadata) failed with exit code '1'
NOTE: Tasks Summary: Attempted 3173 tasks of which 3172 didn't need to be rerun and 1 failed.
Summary: 1 task failed:
/media/fff/disk1T/yocto/demo3/poky/meta/recipes-kernel/linux/linux-yocto-rt_5.4.bb:do_kernel_metadata
Summary: There were 2 ERROR messages shown, returning a non-zero exit code.
My hardware cpu is x86-64 core. It hint genericx86-64/preempt-rt dont exist, what action should I adapt to generate core-image-sato with preempt-RT? Please leave a comment and help me if you are similar with this problem.
I try to checkout various branch of yocto but doesn't matter.These dunfell、langdale、kirkstone.I expect to use dunfell.
Following is my build/conf/bblayers.conf:
POKY_BBLAYERS_CONF_VERSION = "2"
BBPATH = "${TOPDIR}"
BBFILES ?= ""
BBLAYERS ?= " \
/media/fff/disk1T/yocto/demo3/poky/meta \
/media/fff/disk1T/yocto/demo3/poky/meta-poky \
/media/fff/disk1T/yocto/demo3/poky/meta-yocto-bsp \
"

Why is anyhow not working in the stable version?

I have a clean project to which I include anyhow 1.0.66.
Installed the latest version of rust.
I'm getting an error saying that anyhow requires a nightly version. Perhaps this is due to the use of backtrace, but it is supported in rust version 1.65. I don't understand how to solve the problem.
Cargo.toml
[package]
name = "libfs"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = {version = "1.22", features = ["full"]}
anyhow = {version = "1.0.66", features = ["default"]}
src/lib.rs
#[tokio::test]
async fn run_test() {
println!("test");
}
output
$ cargo build
Compiling anyhow v1.0.66
error[E0554]: `#![feature]` may not be used on the stable release channel
--> /home/dima/.cargo/registry/src/github.com-1ecc6299db9ec823/anyhow-1.0.66/src/lib.rs:214:32
|
214 | #![cfg_attr(backtrace, feature(error_generic_member_access, provide_any))]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0554]: `#![feature]` may not be used on the stable release channel
--> /home/dima/.cargo/registry/src/github.com-1ecc6299db9ec823/anyhow-1.0.66/src/lib.rs:214:61
|
214 | #![cfg_attr(backtrace, feature(error_generic_member_access, provide_any))]
| ^^^^^^^^^^^
For more information about this error, try `rustc --explain E0554`.
error: could not compile `anyhow` due to 2 previous errors
The problem was solved by:
rm -rf target
cargo check
This seems to be related to dtolnay/anyhow/issues/250 and rust-lang/rust-analyzer/issues/12973.

Failed build Yocto Gatesgarth "extensible SDK" (eSDK) - populate_sdk_ext fail

I'm working with Yocto "Gatesgarth" on a custom board based on i.MX6ULL.
I'm facing some problems in generating the extensible SDK (eSDK).
The generation of normal SDK it's accomplished correctly.
Below some details.
Details of system:
Board based on NXP i.MX6ULL
Yocto version "Gatesgarth 3.2.4 (May 2021)"
BB_VERSION = "1.48.0",
NATIVELSBSTRING = "ubuntu-18.04"
DISTRO_VERSION = "5.10-gatesgarth"
meta-qt5 is present
Build environment based on Docker Container
Environment Variable:
File: conf/local.conf
SDKMACHINE ?= 'x86_64'
File: test-image-mx6ull.bb
inherit core-image
inherit populate_sdk_qt5
inherit populate_sdk_ext
SDK_EXT_TYPE = "minimal"
SDK_INCLUDE_TOOLCHAIN = "1"
SDK_INCLUDE_PKGDATA = "0"
SDK_INCLUDE_NATIVESDK = "1"
The command executed is :
bitbake test-image-mx6ull -c populate_sdk_ext
Output:
ERROR: test-image-mx6ull-1.0-r0 do_populate_sdk_ext: Error executing a python function in exec_python_func() autogenerated:
The stack trace of python calls that resulted in this exception/failure was:
File: 'exec_python_func() autogenerated', lineno: 2, function: <module>
0001:
*** 0002:do_populate_sdk_ext(d)
0003:
File: '/yocto/sources/poky/meta/classes/populate_sdk_ext.bbclass', lineno: 720, function: do_populate_sdk_ext
0716: bb.fatal('The extensible SDK can currently only be built for the same architecture as the machine being built on - SDK_ARCH is set to %s (likely via setting
SDKMACHINE) which is different from the architecture of the build machine (%s). Unable to continue.' % (d.getVar('SDK_ARCH'), d.getVar('BUILD_ARCH')))
0717:
0718: d.setVar('SDK_INSTALL_TARGETS', get_sdk_install_targets(d))
0719: if d.getVar('SDK_INCLUDE_BUILDTOOLS') == '1':
*** 0720: buildtools_fn = get_current_buildtools(d)
0721: else:
0722: buildtools_fn = None
0723: d.setVar('SDK_REQUIRED_UTILITIES', get_sdk_required_utilities(buildtools_fn, d))
0724: d.setVar('SDK_BUILDTOOLS_INSTALLER', buildtools_fn)
File: '/yocto/sources/poky/meta/classes/populate_sdk_ext.bbclass', lineno: 556, function: get_current_buildtools
0552: import glob
0553: btfiles = glob.glob(os.path.join(d.getVar('SDK_DEPLOY'), '*-buildtools-nativesdk-standalone-*.sh'))
0554: btfiles.sort(key=os.path.getctime)
0555: print("MY-DEBUG - btfiles = {} - SDK_DEPLOY = {}".format(btfiles, d.getVar('SDK_DEPLOY')))
*** 0556: return os.path.basename(btfiles[-1])
0557:
0558:def get_sdk_required_utilities(buildtools_fn, d):
0559: """Find required utilities that aren't provided by the buildtools"""
0560: sanity_required_utilities = (d.getVar('SANITY_REQUIRED_UTILITIES') or '').split()
Exception: IndexError: list index out of range
DEBUG: Python function do_populate_sdk_ext finished
MY-DEBUG - btfiles = [] - SDK_DEPLOY = /yocto/build-mX6ull/tmp/deploy/sdk
Question:
In line 553 the array btfiles should be filled,
but the array is empty and the line 556 generate the exception.
I have no idea of whats is wrong, what I have forget and what Yocto environment variables are needed to setup to do a correctly work.
hope you are doing good
i had similar issue where i couldnt populate esdk,
its all in GLIBC version..
kindly update your GLIBC version
In my case i had to update GLIBC version to 2.33 in "yocto-uninative.inc" file. It worked for me!!!

Why does the homrebrew formula test fail with a serde_json error "expected value at line 1 column 1"

I have a rust lib that I compile with cargo and the resulting binary should bundle a folder of json files. Those json files are read by my program via:
let filename = "./fonts/console.json";
let data = read_to_string(Path::new(filename).as_os_str())
.unwrap_or(format!("Unable to read file \"{}\"", color(filename, Colors::Red)));
serde_json::from_str(&data).unwrap_or_else(|error| {
panic!(
"JSON parsing error encountered for: \"{}\"\nError: {}",
color(filename, Colors::Red),
color(&format!("{}", error), Colors::Yellow)
)
})
When I run cargo build --release I get a binary that I run with like this:
λ my_thing test
test
And the code path for the rust code above is triggered without any errors.
I also like to add that cargo install mything works as expected as well. No issues which makes me think this is not a cargo bundle compile issue...?!
Now I'm trying to publish this lib on homebrew so I wrote this formula:
class Mything < Formula
desc "Description etc"
homepage "https://hpomepage.com"
url "https://github.com/path/to/archive/refs/tags/v3.0.0.tar.gz"
sha256 "547a8e3059e1543debd8e0f10e9efd05c27d13b0717echs7634e1c4cf49d44cb"
license "GPL-3.0-or-later"
depends_on "rust" => :build
def install
chdir "rust" do
system "make"
system "cargo", "build", "--release", "--bin", "mything"
bin.install "target/release/mything"
end
end
test do
print "#{bin}/mything test -f console\n"
# ^-- I added this for debugging to make 100% sure I'm not getting the binaries mixed up
assert_match "\n\n\ntest\n\n\n",
shell_output("#{bin}/mything test -f console")
end
end
Installing this works fine but when I run brew test mything I get:
λ brew test mything
==> Testing mything
/opt/homebrew/Cellar/mything/3.0.0/bin/mything test -f console
==> /opt/homebrew/Cellar/mything/3.0.0/bin/mything test -f console
thread 'main' panicked at 'JSON parsing error encountered for: "./fonts/console.json"
Error: expected value at line 1 column 1', src/font.rs:88:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Error: mything: failed
An exception occurred within a child process:
Minitest::Assertion: Expected: 0
Actual: 101
/opt/homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/minitest-5.15.0/lib/minitest/assertions.rb:183:in `assert'
/opt/homebrew/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/minitest-5.15.0/lib/minitest/assertions.rb:218:in `assert_equal'
/opt/homebrew/Library/Homebrew/formula_assertions.rb:26:in `shell_output'
/opt/homebrew/Library/Taps/homebrew/homebrew-core/Formula/mything.rb:21:in `block in <class:Mything>'
/opt/homebrew/Library/Homebrew/formula.rb:2112:in `block (3 levels) in run_test'
/opt/homebrew/Library/Homebrew/utils.rb:595:in `with_env'
/opt/homebrew/Library/Homebrew/formula.rb:2111:in `block (2 levels) in run_test'
/opt/homebrew/Library/Homebrew/formula.rb:948:in `with_logging'
/opt/homebrew/Library/Homebrew/formula.rb:2110:in `block in run_test'
/opt/homebrew/Library/Homebrew/mktemp.rb:63:in `block in run'
/opt/homebrew/Library/Homebrew/mktemp.rb:63:in `chdir'
/opt/homebrew/Library/Homebrew/mktemp.rb:63:in `run'
/opt/homebrew/Library/Homebrew/formula.rb:2363:in `mktemp'
/opt/homebrew/Library/Homebrew/formula.rb:2104:in `run_test'
/opt/homebrew/Library/Homebrew/test.rb:43:in `block in <main>'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/timeout.rb:93:in `block in timeout'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/timeout.rb:33:in `block in catch'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/timeout.rb:33:in `catch'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/timeout.rb:33:in `catch'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/timeout.rb:108:in `timeout'
/opt/homebrew/Library/Homebrew/test.rb:48:in `<main>'
Now I copy the printed first line of that output and run it the same way:
λ /opt/homebrew/Cellar/mything/3.0.0/bin/mything test -f console
test
And it works. That's the very same binary that brew is testing here.
I don't know much ruby so there is a good chance I'm getting the test wrong somehow?
I also tried to do this in the test:
system bin/"cfonts", "test", "-f", "console"
Which also fails with the same error.
When I run that binary now since it's installed via brew and in my PATH it all works as well which is nuts...
λ mything test -f console
test
λ which mything
/opt/homebrew/bin/mything
Any help is appreciated.
The issue was that of course the relative path was only working in certain directories where that folder was present.
A rust issue after-all.
So I used the include_str macro to include the contents of the json file into the binary at compile time:
let font_content = include_str!("../fonts/console.json");
serde_json::from_str(&font_content).unwrap_or_else(|error| {
panic!(
"JSON parsing error encountered for: \"{}\"\nError: {}",
color(filename, Colors::Red),
color(&format!("{}", error), Colors::Yellow)
)
})
Now the brew formula works fine:
class Mything < Formula
desc "Description etc"
homepage "https://hpomepage.com"
url "https://github.com/path/to/archive/refs/tags/v3.0.0.tar.gz"
sha256 "547a8e3059e1543debd8e0f10e9efd05c27d13b0717echs7634e1c4cf49d44cb"
license "GPL-3.0-or-later"
depends_on "rust" => :build
def install
chdir "rust" do
system "make"
system "cargo", "build", "--release", "--bin", "mything"
bin.install "target/release/mything"
end
end
test do
assert_match "\n\n\ntest\n\n\n",
shell_output("#{bin}/mything test -f console")
end
end
λ brew test cfonts
==> Testing cfonts
==> /opt/homebrew/Cellar/mything/3.0.0/bin/mything test -f console

How do I zip files in bazel

I have a set of files as part of the my repository. How do I produce a zip file out of those files in bazel. I found a rules for tar.gz etc. but cannot find a way how to achive a zip archive.
Found references mentioning zipper but couldn't figure out how to load it and use it. Can someone more experienced with bazel help?
A basic pkg_zip rule was added to rules_pkg recently. Here is a basic usage example from the unit tests:
load("#rules_pkg//:pkg.bzl", "pkg_zip")
pkg_zip(
name = "test_zip_basic",
srcs = [
"testdata/hello.txt",
"testdata/loremipsum.txt",
],
)
You can specify the paths using the extra rules in mappings.bzl. Here is the example given by the Bazel team:
load("#rules_pkg//:mappings.bzl", "pkg_attributes", "pkg_filegroup", "pkg_files", "pkg_mkdirs", "strip_prefix")
load("#rules_pkg//:pkg.bzl", "pkg_tar", "pkg_zip")
# This is the top level BUILD for a hypothetical project Foo. It has a client,
# a server, docs, and runtime directories needed by the server.
# We want to ship it for Linux, macOS, and Windows.
#
# This example shows various techniques for specifying how your source tree
# transforms into the installation tree. As such, it favors using a lot of
# distict features, at the expense of uniformity.
pkg_files(
name = "share_doc",
srcs = [
"//docs",
],
# Required, but why?: see #354
strip_prefix = strip_prefix.from_pkg(),
# Where it should be in the final package
prefix = "usr/share/doc/foo",
)
pkg_filegroup(
name = "manpages",
srcs = [
"//src/client:manpages",
"//src/server:manpages",
],
prefix = "/usr/share",
)
pkg_tar(
name = "foo_tar",
srcs = [
"README.txt",
":manpages",
":share_doc",
"//resources/l10n:all",
"//src/client:arch",
"//src/server:arch",
],
)
pkg_zip(
name = "foo_zip",
srcs = [
"README.txt",
":manpages",
":share_doc",
"//resources/l10n:all",
"//src/client:arch",
"//src/server:arch",
],
)
The zipper utility is at #bazel_tools//tools/zip:zipper, this is its usage:
Usage: zipper [vxc[fC]] x.zip [-d exdir] [[zip_path1=]file1 ... [zip_pathn=]filen]
v verbose - list all file in x.zip
x extract - extract files in x.zip to current directory, or
an optional directory relative to the current directory
specified through -d option
c create - add files to x.zip
f flatten - flatten files to use with create or extract operation
C compress - compress files when using the create operation
x and c cannot be used in the same command-line.
For every file, a path in the zip can be specified. Examples:
zipper c x.zip a/b/__init__.py= # Add an empty file at a/b/__init__.py
zipper c x.zip a/b/main.py=foo/bar/bin.py # Add file foo/bar/bin.py at a/b/main.py
If the zip path is not specified, it is assumed to be the file path.
So it can be used in a genrule like this:
$ tree
.
├── BUILD
├── dir
│   ├── a
│   ├── b
│   └── c
└── WORKSPACE
1 directory, 5 files
$ cat BUILD
genrule(
name = "gen_zip",
srcs = glob(["dir/*"]),
tools = ["#bazel_tools//tools/zip:zipper"],
outs = ["files.zip"],
cmd = "$(location #bazel_tools//tools/zip:zipper) c $# $(SRCS)",
)
$ bazel build :files.zip
INFO: Analyzed target //:files.zip (7 packages loaded, 41 targets configured).
INFO: Found 1 target...
Target //:files.zip up-to-date:
bazel-bin/files.zip
INFO: Elapsed time: 0.653s, Critical Path: 0.08s
INFO: 1 process: 1 linux-sandbox.
INFO: Build completed successfully, 2 total actions
$ unzip -l bazel-bin/files.zip
Archive: bazel-bin/files.zip
Length Date Time Name
--------- ---------- ----- ----
0 2010-01-01 00:00 dir/a
0 2010-01-01 00:00 dir/b
0 2010-01-01 00:00 dir/c
--------- -------
0 3 files
It can similarly be used in Starlark:
def _some_rule_impl(ctx):
zipper_inputs = []
zipper_args = ctx.actions.args()
zipper_args.add("c", ctx.outputs.zip.path)
....
ctx.actions.run(
inputs = zipper_inputs,
outputs = [ctx.outputs.zip],
executable = ctx.executable._zipper,
arguments = [zipper_args],
progress_message = "Creating zip...",
mnemonic = "zipper",
)
some_rule = rule(
implementation = _some_rule_impl,
attrs = {
"deps": attr.label_list(),
"$zipper": attr.label(default = Label("#bazel_tools//tools/zip:zipper"), cfg = "host", executable=True),
},
outputs = {"zip": "%{name}.zip"},
)

Resources