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