fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
8b8150db
cleanup
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 199 200tools = get_rust_tools ( 201cargo_template = cargo_template , 202rustc_template = rustc_template , 203host_triple = host_triple , 204channel = channel , 205version = version , 206) 207 208binary_name = repository_ctx . attr . binary or repository_ctx . name 209 210# In addition to platform specific environment variables, a common set (indicated by `*`) will always 211# be gathered. 212environment = dict ( _collect_environ ( repository_ctx , "*" ). items () + _collect_environ ( repository_ctx , host_triple . str ). items ()) 213 214cargo_config = None 215if repository_ctx . attr . cargo_config : 216cargo_config = repository_ctx . path ( repository_ctx . attr . cargo_config ) 217 218built_binary = cargo_bootstrap ( 219repository_ctx = repository_ctx , 220cargo_bin = repository_ctx . path ( tools . cargo ), 221rustc_bin = repository_ctx . path ( tools . rustc ), 222cargo_config = cargo_config , 223binary = binary_name , 224cargo_manifest = repository_ctx . path ( repository_ctx . attr . cargo_toml ), 225build_mode = repository_ctx . attr . build_mode , 226environment = environment , 227timeout = repository_ctx . attr . timeout , 228) 229 230# Create a symlink so that the binary can be accesed via it's target name 231repository_ctx . symlink ( built_binary , binary_name ) 232 233repository_ctx . file ( "BUILD.bazel" , _BUILD_FILE_CONTENT . format ( 234binary_name = binary_name , 235binary = built_binary , 236)) 237 238cargo_bootstrap_repository = repository_rule ( 239doc = "A rule for bootstrapping a Rust binary using [Cargo](https://doc.rust-lang.org/cargo/)" , 240implementation = _cargo_bootstrap_repository_impl , 241attrs = { 242"binary" : attr . string ( 243doc = "The binary to build (the `--bin` parameter for Cargo). If left empty, the repository name will be used." , 244), 245"build_mode" : attr . string ( 246doc = "The build mode the binary should be built with" , 247values = [ 248"debug" , 249"release" , 250], 251default = "release" , 252), 253"cargo_config" : attr . label ( 254doc = "The path of the Cargo configuration (`Config.toml`) file." , 255allow_single_file = True , 256), 257"cargo_lockfile" : attr . label ( 258doc = "The lockfile of the crate_universe resolver" , 259allow_single_file = [ "Cargo.lock" ], 260mandatory = True , 261), 262"cargo_toml" : attr . label ( 263doc = "The path of the `Cargo.toml` file." , 264allow_single_file = [ "Cargo.toml" ], 265mandatory = True , 266), 267"env" : attr . string_dict ( 268doc = ( 269"A mapping of platform triple to a set of environment variables. See " + 270"[cargo_env](#cargo_env) for usage details. Additionally, the platform triple `*` applies to all platforms." 271), 272), 273"env_label" : attr . string_dict ( 274doc = ( 275"A mapping of platform triple to a set of environment variables. This " + 276"attribute differs from `env` in that all variables passed here must be " + 277"fully qualified labels of files. See [cargo_env](#cargo_env) for usage details. " + 278"Additionally, the platform triple `*` applies to all platforms." 279), 280), 281"rust_toolchain_cargo_template" : attr . string ( 282doc = ( 283"The template to use for finding the host `cargo` binary. `{version}` (eg. '1.53.0'), " + 284"`{triple}` (eg. 'x86_64-unknown-linux-gnu'), `{arch}` (eg. 'aarch64'), `{vendor}` (eg. 'unknown'), " + 285"`{system}` (eg. 'darwin'), `{channel}` (eg. 'stable'), and `{tool}` (eg. 'rustc.exe') will be " + 286"replaced in the string if present." 287), 288default = "@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}" , 289), 290"rust_toolchain_rustc_template" : attr . string ( 291doc = ( 292"The template to use for finding the host `rustc` binary. `{version}` (eg. '1.53.0'), " + 293"`{triple}` (eg. 'x86_64-unknown-linux-gnu'), `{arch}` (eg. 'aarch64'), `{vendor}` (eg. 'unknown'), " + 294"`{system}` (eg. 'darwin'), `{channel}` (eg. 'stable'), and `{tool}` (eg. 'rustc.exe') will be " + 295"replaced in the string if present." 296), 297default = "@rust_{system}_{arch}__{triple}__{channel}_tools//:bin/{tool}" , 298), 299"srcs" : attr . label_list ( 300doc = "Souce files of the crate to build. Passing source files here can be used to trigger rebuilds when changes are made" , 301allow_files = True , 302), 303"timeout" : attr . int ( 304doc = "Maximum duration of the Cargo build command in seconds" , 305default = 600 , 306), 307"version" : attr . string ( 308doc = "The version of Rust the currently registered toolchain is using. Eg. `1.56.0`, or `nightly/2021-09-08`" , 309default = rust_common . default_version , 310), 311}, 312) 313 314def cargo_env ( env ): 315"""A helper for generating platform specific environment variables 316 317```python 318load("@rules_rust//rust:defs.bzl", "rust_common") 319load("@rules_rust//cargo:defs.bzl", "cargo_bootstrap_repository", "cargo_env") 320 321cargo_bootstrap_repository( 322name = "bootstrapped_bin", 323cargo_lockfile = "//:Cargo.lock", 324cargo_toml = "//:Cargo.toml", 325srcs = ["//:resolver_srcs"], 326version = rust_common.default_version, 327binary = "my-crate-binary", 328env = { 329"x86_64-unknown-linux-gnu": cargo_env({ 330"FOO": "BAR", 331}), 332}, 333env_label = { 334"aarch64-unknown-linux-musl": cargo_env({ 335"DOC": "//:README.md", 336}), 337} 338) 339``` 340 341Args: 342env (dict): A map of environment variables 343 344Returns: 345str: A json encoded string of the environment variables 346""" 347return json . encode ( dict ( env ))