fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
674762f6
0.9.0
1"""The `cargo_bootstrap` rule is used for bootstrapping cargo binaries in a repository rule.""" 2 3load ( "//cargo/private:cargo_utils.bzl" , "get_rust_tools" ) 4load ( "//rust:defs.bzl" , "rust_common" ) 5load ( "//rust/platform:triple.bzl" , "get_host_triple" ) 6 7_CARGO_BUILD_MODES = [ 8"release" , 9"debug" , 10] 11 12_FAIL_MESSAGE = """\ 13Process exited with code '{code}' 14# ARGV ######################################################################## 15{argv} 16 17# STDOUT ###################################################################### 18{stdout} 19 20# STDERR ###################################################################### 21{stderr} 22""" 23 24def cargo_bootstrap ( 25repository_ctx , 26cargo_bin , 27rustc_bin , 28binary , 29cargo_manifest , 30environment = {}, 31quiet = False , 32build_mode = "release" , 33target_dir = None , 34timeout = 600 ): 35"""A function for bootstrapping a cargo binary within a repository rule 36 37Args: 38repository_ctx (repository_ctx): The rule's context object. 39cargo_bin (path): The path to a Cargo binary. 40rustc_bin (path): The path to a Rustc binary. 41binary (str): The binary to build (the `--bin` parameter for Cargo). 42cargo_manifest (path): The path to a Cargo manifest (Cargo.toml file). 43environment (dict): Environment variables to use during execution. 44quiet (bool, optional): Whether or not to print output from the Cargo command. 45build_mode (str, optional): The build mode to use 46target_dir (path, optional): The directory in which to produce build outputs 47(Cargo's --target-dir argument). 48timeout (int, optional): Maximum duration of the Cargo build command in seconds, 49 50Returns: 51path: The path of the built binary within the target directory 52""" 53 54if not target_dir : 55target_dir = repository_ctx . path ( "." ) 56 57args = [ 58cargo_bin , 59"build" , 60"--bin" , 61binary , 62"--locked" , 63"--target-dir" , 64target_dir , 65"--manifest-path" , 66cargo_manifest , 67] 68 69if build_mode not in _CARGO_BUILD_MODES : 70fail ( "'{}' is not a supported build mode. Use one of {}" . format ( build_mode , _CARGO_BUILD_MODES )) 71 72if build_mode == "release" : 73args . append ( "--release" ) 74 75env = dict ({ 76"RUSTC" : str ( rustc_bin ), 77}. items () + environment . items ()) 78 79repository_ctx . report_progress ( "Cargo Bootstrapping {}" . format ( binary )) 80result = repository_ctx . execute ( 81args , 82environment = env , 83quiet = quiet , 84timeout = timeout , 85) 86 87if result . return_code != 0 : 88fail ( _FAIL_MESSAGE . format ( 89code = result . return_code , 90argv = args , 91stdout = result . stdout , 92stderr = result . stderr , 93)) 94 95extension = "" 96if "win" in repository_ctx . os . name : 97extension = ".exe" 98 99binary_path = "{}/{}{}" . format ( 100build_mode , 101binary , 102extension , 103) 104 105if not repository_ctx . path ( binary_path ). exists : 106fail ( "Failed to produce binary at {}" . format ( binary_path )) 107 108return binary_path 109 110_BUILD_FILE_CONTENT = """\ 111load("@rules_rust//rust:defs.bzl", "rust_binary") 112 113package(default_visibility = ["//visibility:public"]) 114 115exports_files([ 116"{binary_name}", 117"{binary}" 118]) 119 120alias( 121name = "binary", 122actual = "{binary}", 123) 124 125rust_binary( 126name = "install", 127rustc_env = {{ 128"RULES_RUST_CARGO_BOOTSTRAP_BINARY": "$(rootpath {binary})" 129}}, 130data = [ 131"{binary}", 132], 133srcs = [ 134"@rules_rust//cargo/bootstrap:bootstrap_installer.rs" 135], 136) 137""" 138 139def _collect_environ ( repository_ctx , host_triple ): 140"""Gather environment varialbes to use from the current rule context 141 142Args: 143repository_ctx (repository_ctx): The rule's context object. 144host_triple (str): A string of the current host triple 145 146Returns: 147dict: A map of environment variables 148""" 149env_vars = dict ( json . decode ( repository_ctx . attr . env . get ( host_triple , "{}" ))) 150 151# Gather the path for each label and ensure it exists 152env_labels = dict ( json . decode ( repository_ctx . attr . env_label . get ( host_triple , "{}" ))) 153env_labels = { key : repository_ctx . path ( Label ( value )) for ( key , value ) in env_labels . items ()} 154for key in env_labels : 155if not env_labels [ key ]. exists : 156fail ( "File for key '{}' does not exist: {}" , key , env_labels [ key ]) 157env_labels = { key : str ( value ) for ( key , value ) in env_labels . items ()} 158 159return dict ( env_vars . items () + env_labels . items ()) 160 161def _detect_changes ( repository_ctx ): 162"""Inspect files that are considered inputs to the build for changes 163 164Args: 165repository_ctx (repository_ctx): The rule's context object. 166""" 167# Simply generating a `path` object consideres the file as 'tracked' or 168# 'consumed' which means changes to it will trigger rebuilds 169 170for src in repository_ctx . attr . srcs : 171repository_ctx . path ( src ) 172 173repository_ctx . path ( repository_ctx . attr . cargo_lockfile ) 174repository_ctx . path ( repository_ctx . attr . cargo_toml ) 175 176def _cargo_bootstrap_repository_impl ( repository_ctx ): 177# Pretend to Bazel that this rule's input files have been used, so that it will re-run the rule if they change. 178_detect_changes ( repository_ctx ) 179 180if repository_ctx . attr . version in ( "beta" , "nightly" ): 181version_str = "{}-{}" . format ( repository_ctx . attr . version , repository_ctx . attr . iso_date ) 182else : 183version_str = repository_ctx . attr . version 184 185host_triple = get_host_triple ( repository_ctx ) 186 187if repository_ctx . attr . rust_toolchain_repository_template : 188# buildifier: disable=print 189( "Warning: `rust_toolchain_repository_template` is deprecated. Please use `rust_toolchain_cargo_template` and `rust_toolchain_rustc_template`" ) 190cargo_template = "@{}{}" . format ( repository_ctx . attr . rust_toolchain_repository_template , "//:bin/{tool}" ) 191rustc_template = "@{}{}" . format ( repository_ctx . attr . rust_toolchain_repository_template , "//:bin/{tool}" ) 192else : 193cargo_template = repository_ctx . attr . rust_toolchain_cargo_template 194rustc_template = repository_ctx . attr . rust_toolchain_rustc_template 195 196tools = get_rust_tools ( 197cargo_template = cargo_template , 198rustc_template = rustc_template , 199host_triple = host_triple , 200version = version_str , 201) 202 203binary_name = repository_ctx . attr . binary or repository_ctx . name 204 205# In addition to platform specific environment variables, a common set (indicated by `*`) will always 206# be gathered. 207environment = dict ( _collect_environ ( repository_ctx , "*" ). items () + _collect_environ ( repository_ctx , host_triple . str ). items ()) 208 209built_binary = cargo_bootstrap ( 210repository_ctx = repository_ctx , 211cargo_bin = repository_ctx . path ( tools . cargo ), 212rustc_bin = repository_ctx . path ( tools . rustc ), 213binary = binary_name , 214cargo_manifest = repository_ctx . path ( repository_ctx . attr . cargo_toml ), 215build_mode = repository_ctx . attr . build_mode , 216environment = environment , 217timeout = repository_ctx . attr . timeout , 218) 219 220# Create a symlink so that the binary can be accesed via it's target name 221repository_ctx . symlink ( built_binary , binary_name ) 222 223repository_ctx . file ( "BUILD.bazel" , _BUILD_FILE_CONTENT . format ( 224binary_name = binary_name , 225binary = built_binary , 226)) 227 228cargo_bootstrap_repository = repository_rule ( 229doc = "A rule for bootstrapping a Rust binary using [Cargo](https://doc.rust-lang.org/cargo/)" , 230implementation = _cargo_bootstrap_repository_impl , 231attrs = { 232"binary" : attr . string ( 233doc = "The binary to build (the `--bin` parameter for Cargo). If left empty, the repository name will be used." , 234), 235"build_mode" : attr . string ( 236doc = "The build mode the binary should be built with" , 237values = [ 238"debug" , 239"release" , 240], 241default = "release" , 242), 243"cargo_lockfile" : attr . label ( 244doc = "The lockfile of the crate_universe resolver" , 245allow_single_file = [ "Cargo.lock" ], 246mandatory = True , 247), 248"cargo_toml" : attr . label ( 249doc = "The path of the crate_universe resolver manifest (`Cargo.toml` file)" , 250allow_single_file = [ "Cargo.toml" ], 251mandatory = True , 252), 253"env" : attr . string_dict ( 254doc = ( 255"A mapping of platform triple to a set of environment variables. See " + 256"[cargo_env](#cargo_env) for usage details. Additionally, the platform triple `*` applies to all platforms." 257), 258), 259"env_label" : attr . string_dict ( 260doc = ( 261"A mapping of platform triple to a set of environment variables. This " + 262"attribute differs from `env` in that all variables passed here must be " + 263"fully qualified labels of files. See [cargo_env](#cargo_env) for usage details. " + 264"Additionally, the platform triple `*` applies to all platforms." 265), 266), 267"iso_date" : attr . string ( 268doc = "The iso_date of cargo binary the resolver should use. Note: This can only be set if `version` is `beta` or `nightly`" , 269), 270"rust_toolchain_cargo_template" : attr . string ( 271doc = ( 272"The template to use for finding the host `cargo` binary. `{version}` (eg. '1.53.0'), " + 273"`{triple}` (eg. 'x86_64-unknown-linux-gnu'), `{arch}` (eg. 'aarch64'), `{vendor}` (eg. 'unknown'), " + 274"`{system}` (eg. 'darwin'), and `{tool}` (eg. 'rustc.exe') will be replaced in the string if present." 275), 276default = "@rust_{system}_{arch}__{triple}_tools//:bin/{tool}" , 277), 278"rust_toolchain_repository_template" : attr . string ( 279doc = "**Deprecated**: Please use `rust_toolchain_cargo_template` and `rust_toolchain_rustc_template`" , 280), 281"rust_toolchain_rustc_template" : attr . string ( 282doc = ( 283"The template to use for finding the host `rustc` binary. `{version}` (eg. '1.53.0'), " + 284"`{triple}` (eg. 'x86_64-unknown-linux-gnu'), `{arch}` (eg. 'aarch64'), `{vendor}` (eg. 'unknown'), " + 285"`{system}` (eg. 'darwin'), and `{tool}` (eg. 'rustc.exe') will be replaced in the string if present." 286), 287default = "@rust_{system}_{arch}__{triple}_tools//:bin/{tool}" , 288), 289"srcs" : attr . label_list ( 290doc = "Souce files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are made" , 291allow_files = True , 292), 293"timeout" : attr . int ( 294doc = "Maximum duration of the Cargo build command in seconds" , 295default = 600 , 296), 297"version" : attr . string ( 298doc = "The version of cargo the resolver should use" , 299default = rust_common . default_version , 300), 301"_cc_toolchain" : attr . label ( 302default = Label ( "@bazel_tools//tools/cpp:current_cc_toolchain" ), 303), 304}, 305) 306 307def cargo_env ( env ): 308"""A helper for generating platform specific environment variables 309 310```python 311load("@rules_rust//rust:defs.bzl", "rust_common") 312load("@rules_rust//cargo:defs.bzl", "cargo_bootstrap_repository", "cargo_env") 313 314cargo_bootstrap_repository( 315name = "bootstrapped_bin", 316cargo_lockfile = "//:Cargo.lock", 317cargo_toml = "//:Cargo.toml", 318srcs = ["//:resolver_srcs"], 319version = rust_common.default_version, 320binary = "my-crate-binary", 321env = { 322"x86_64-unknown-linux-gnu": cargo_env({ 323"FOO": "BAR", 324}), 325}, 326env_label = { 327"aarch64-unknown-linux-musl": cargo_env({ 328"DOC": "//:README.md", 329}), 330} 331) 332``` 333 334Args: 335env (dict): A map of environment variables 336 337Returns: 338str: A json encoded string of the environment variables 339""" 340return json . encode ( dict ( env ))