fork/rules_rust

git clone https://git.julia.blue/fork/rules_rust

Daniel Wagner-HallImprove workspace discovery logic (#3030)72556e5e

main
29.8 KiB712 linesraw
1"""Module extension for generating third-party crates for use in bazel."""
2
3load("@bazel_features//:features.bzl", "bazel_features")
4load("@bazel_skylib//lib:structs.bzl", "structs")
5load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository")
6load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
7load("//crate_universe/private:crates_vendor.bzl", "CRATES_VENDOR_ATTRS", "generate_config_file", "generate_splicing_manifest")
8load("//crate_universe/private:generate_utils.bzl", "CARGO_BAZEL_GENERATOR_SHA256", "CARGO_BAZEL_GENERATOR_URL", "GENERATOR_ENV_VARS", "render_config")
9load("//crate_universe/private:local_crate_mirror.bzl", "local_crate_mirror")
10load("//crate_universe/private:urls.bzl", "CARGO_BAZEL_SHA256S", "CARGO_BAZEL_URLS")
11load("//rust/platform:triple.bzl", "get_host_triple")
12load("//rust/platform:triple_mappings.bzl", "system_to_binary_ext")
13load(":defs.bzl", _crate_universe_crate = "crate")
14
15# A list of labels which may be relative (and if so, is within the repo the rule is generated in).
16#
17# If I were to write ":foo", with attr.label_list, it would evaluate to
18# "@@//:foo". However, for a tag such as deps, ":foo" should refer to
19# "@@rules_rust~crates~<crate>//:foo".
20_relative_label_list = attr.string_list
21
22_OPT_BOOL_VALUES = {
23    "auto": None,
24    "off": False,
25    "on": True,
26}
27
28def _get_or_insert(d, key, value):
29    if key not in d:
30        d[key] = value
31    return d[key]
32
33def _generate_repo_impl(repo_ctx):
34    for path, contents in repo_ctx.attr.contents.items():
35        repo_ctx.file(path, contents)
36
37_generate_repo = repository_rule(
38    doc = "A utility for generating a hub repo.",
39    implementation = _generate_repo_impl,
40    attrs = {
41        "contents": attr.string_dict(
42            doc = "A mapping of file names to text they should contain.",
43            mandatory = True,
44        ),
45    },
46)
47
48def _annotations_for_repo(module_annotations, repo_specific_annotations):
49    """Merges the set of global annotations with the repo-specific ones
50
51    Args:
52        module_annotations (dict): The annotation tags that apply to all repos, keyed by crate.
53        repo_specific_annotations (dict): The annotation tags that apply to only this repo, keyed by crate.
54    """
55
56    if not repo_specific_annotations:
57        return module_annotations
58
59    annotations = dict(module_annotations)
60    for crate, values in repo_specific_annotations.items():
61        _get_or_insert(annotations, crate, []).extend(values)
62    return annotations
63
64def _generate_hub_and_spokes(*, module_ctx, cargo_bazel, cfg, annotations, cargo_lockfile = None, manifests = {}, packages = {}):
65    """Generates repositories for the transitive closure of crates defined by manifests and packages.
66
67    Args:
68        module_ctx (module_ctx): The module context object.
69        cargo_bazel (function): A function that can be called to execute cargo_bazel.
70        cfg (object): The module tag from `from_cargo` or `from_specs`
71        annotations (dict): The set of annotation tag classes that apply to this closure, keyed by crate name.
72        cargo_lockfile (path): Path to Cargo.lock, if we have one. This is optional for `from_specs` closures.
73        manifests (dict): The set of Cargo.toml manifests that apply to this closure, if any, keyed by path.
74        packages (dict): The set of extra cargo crate tags that apply to this closure, if any, keyed by package name.
75    """
76
77    tag_path = module_ctx.path(cfg.name)
78
79    rendering_config = json.decode(render_config(
80        regen_command = "Run 'cargo update [--workspace]'",
81    ))
82    config_file = tag_path.get_child("config.json")
83    module_ctx.file(
84        config_file,
85        executable = False,
86        content = generate_config_file(
87            module_ctx,
88            mode = "remote",
89            annotations = annotations,
90            generate_build_scripts = cfg.generate_build_scripts,
91            supported_platform_triples = cfg.supported_platform_triples,
92            generate_target_compatible_with = True,
93            repository_name = cfg.name,
94            output_pkg = cfg.name,
95            workspace_name = cfg.name,
96            generate_binaries = cfg.generate_binaries,
97            render_config = rendering_config,
98            repository_ctx = module_ctx,
99        ),
100    )
101
102    splicing_manifest = tag_path.get_child("splicing_manifest.json")
103    module_ctx.file(
104        splicing_manifest,
105        executable = False,
106        content = generate_splicing_manifest(
107            packages = packages,
108            splicing_config = cfg.splicing_config,
109            cargo_config = cfg.cargo_config,
110            manifests = manifests,
111            manifest_to_path = module_ctx.path,
112        ),
113    )
114
115    nonhermetic_root_bazel_workspace_dir = module_ctx.path(Label("@@//:MODULE.bazel")).dirname
116
117    splicing_output_dir = tag_path.get_child("splicing-output")
118    splice_args = [
119        "splice",
120        "--output-dir",
121        splicing_output_dir,
122        "--config",
123        config_file,
124        "--splicing-manifest",
125        splicing_manifest,
126        "--nonhermetic-root-bazel-workspace-dir",
127        nonhermetic_root_bazel_workspace_dir,
128    ]
129    if cargo_lockfile:
130        splice_args.extend([
131            "--cargo-lockfile",
132            cargo_lockfile,
133        ])
134    cargo_bazel(splice_args)
135
136    # Create a lockfile, since we need to parse it to generate spoke
137    # repos.
138    lockfile_path = tag_path.get_child("lockfile.json")
139    module_ctx.file(lockfile_path, "")
140
141    paths_to_track_file = module_ctx.path("paths-to-track")
142    warnings_output_file = module_ctx.path("warnings-output-file")
143
144    cargo_bazel([
145        "generate",
146        "--cargo-lockfile",
147        cargo_lockfile or splicing_output_dir.get_child("Cargo.lock"),
148        "--config",
149        config_file,
150        "--splicing-manifest",
151        splicing_manifest,
152        "--repository-dir",
153        tag_path,
154        "--metadata",
155        splicing_output_dir.get_child("metadata.json"),
156        "--repin",
157        "--lockfile",
158        lockfile_path,
159        "--nonhermetic-root-bazel-workspace-dir",
160        nonhermetic_root_bazel_workspace_dir,
161        "--paths-to-track",
162        paths_to_track_file,
163        "--warnings-output-path",
164        warnings_output_file,
165    ])
166
167    paths_to_track = json.decode(module_ctx.read(paths_to_track_file))
168    for path in paths_to_track:
169        # This read triggers watching the file at this path and invalidates the repository_rule which will get re-run.
170        # Ideally we'd use module_ctx.watch, but it doesn't support files outside of the workspace, and we need to support that.
171        module_ctx.read(path)
172
173    warnings_output_file = json.decode(module_ctx.read(warnings_output_file))
174    for warning in warnings_output_file:
175        # buildifier: disable=print
176        print("WARN: {}".format(warning))
177
178    crates_dir = tag_path.get_child(cfg.name)
179    _generate_repo(
180        name = cfg.name,
181        contents = {
182            "BUILD.bazel": module_ctx.read(crates_dir.get_child("BUILD.bazel")),
183            "defs.bzl": module_ctx.read(crates_dir.get_child("defs.bzl")),
184        },
185    )
186
187    contents = json.decode(module_ctx.read(lockfile_path))
188
189    for crate in contents["crates"].values():
190        repo = crate["repository"]
191        if repo == None:
192            continue
193        name = crate["name"]
194        version = crate["version"]
195
196        # "+" isn't valid in a repo name.
197        crate_repo_name = "{repo_name}__{name}-{version}".format(
198            repo_name = cfg.name,
199            name = name,
200            version = version.replace("+", "-"),
201        )
202
203        build_file_content = module_ctx.read(crates_dir.get_child("BUILD.%s-%s.bazel" % (name, version)))
204        if "Http" in repo:
205            # Replicates functionality in repo_http.j2.
206            repo = repo["Http"]
207            http_archive(
208                name = crate_repo_name,
209                patch_args = repo.get("patch_args", None),
210                patch_tool = repo.get("patch_tool", None),
211                patches = repo.get("patches", None),
212                remote_patch_strip = 1,
213                sha256 = repo.get("sha256", None),
214                type = "tar.gz",
215                urls = [repo["url"]],
216                strip_prefix = "%s-%s" % (crate["name"], crate["version"]),
217                build_file_content = build_file_content,
218            )
219        elif "Git" in repo:
220            # Replicates functionality in repo_git.j2
221            repo = repo["Git"]
222            kwargs = {}
223            for k, v in repo["commitish"].items():
224                if k == "Rev":
225                    kwargs["commit"] = v
226                else:
227                    kwargs[k.lower()] = v
228            new_git_repository(
229                name = crate_repo_name,
230                init_submodules = True,
231                patch_args = repo.get("patch_args", None),
232                patch_tool = repo.get("patch_tool", None),
233                patches = repo.get("patches", None),
234                shallow_since = repo.get("shallow_since", None),
235                remote = repo["remote"],
236                build_file_content = build_file_content,
237                strip_prefix = repo.get("strip_prefix", None),
238                **kwargs
239            )
240        elif "Path" in repo:
241            options = {
242                "config": rendering_config,
243                "crate_context": crate,
244                "platform_conditions": contents["conditions"],
245                "supported_platform_triples": cfg.supported_platform_triples,
246            }
247            kwargs = {}
248            if len(CARGO_BAZEL_URLS) == 0:
249                kwargs["generator"] = "@cargo_bazel_bootstrap//:cargo-bazel"
250            local_crate_mirror(
251                name = crate_repo_name,
252                options_json = json.encode(options),
253                path = repo["Path"]["path"],
254                **kwargs
255            )
256        else:
257            fail("Invalid repo: expected Http or Git to exist for crate %s-%s, got %s" % (name, version, repo))
258
259def _package_to_json(p):
260    # Avoid adding unspecified properties.
261    # If we add them as empty strings, cargo-bazel will be unhappy.
262    return json.encode({
263        k: v
264        for k, v in structs.to_dict(p).items()
265        if v or k == "default_features"
266    })
267
268def _get_generator(module_ctx):
269    """Query Network Resources to local a `cargo-bazel` binary.
270
271    Based off get_generator in crates_universe/private/generate_utils.bzl
272
273    Args:
274        module_ctx (module_ctx):  The rules context object
275
276    Returns:
277        tuple(path, dict) The path to a 'cargo-bazel' binary. The pairing (dict)
278            may be `None` if there is not need to update the attribute
279    """
280    host_triple = get_host_triple(module_ctx)
281    use_environ = False
282    for var in GENERATOR_ENV_VARS:
283        if var in module_ctx.os.environ:
284            use_environ = True
285
286    if use_environ:
287        generator_sha256 = module_ctx.os.environ.get(CARGO_BAZEL_GENERATOR_SHA256)
288        generator_url = module_ctx.os.environ.get(CARGO_BAZEL_GENERATOR_URL)
289    elif len(CARGO_BAZEL_URLS) == 0:
290        return module_ctx.path(Label("@cargo_bazel_bootstrap//:cargo-bazel"))
291    else:
292        generator_sha256 = CARGO_BAZEL_SHA256S.get(host_triple.str)
293        generator_url = CARGO_BAZEL_URLS.get(host_triple.str)
294
295    if not generator_url:
296        fail((
297            "No generator URL was found either in the `CARGO_BAZEL_GENERATOR_URL` " +
298            "environment variable or for the `{}` triple in the `generator_urls` attribute"
299        ).format(host_triple.str))
300
301    output = module_ctx.path("cargo-bazel.exe" if "win" in module_ctx.os.name else "cargo-bazel")
302
303    # Download the file into place
304    download_kwargs = {
305        "executable": True,
306        "output": output,
307        "url": generator_url,
308    }
309
310    if generator_sha256:
311        download_kwargs.update({"sha256": generator_sha256})
312
313    module_ctx.download(**download_kwargs)
314    return output
315
316def _get_host_cargo_rustc(module_ctx):
317    """A helper function to get the path to the host cargo and rustc binaries.
318
319    Args:
320        module_ctx: The module extension's context.
321    Returns:
322        A tuple of path to cargo, path to rustc.
323    """
324    host_triple = get_host_triple(module_ctx)
325    binary_ext = system_to_binary_ext(host_triple.system)
326
327    cargo_path = str(module_ctx.path(Label("@rust_host_tools//:bin/cargo{}".format(binary_ext))))
328    rustc_path = str(module_ctx.path(Label("@rust_host_tools//:bin/rustc{}".format(binary_ext))))
329    return cargo_path, rustc_path
330
331def _get_cargo_bazel_runner(module_ctx, cargo_bazel):
332    """A helper function to allow executing cargo_bazel in module extensions.
333
334    Args:
335        module_ctx: The module extension's context.
336        cargo_bazel: Path The path to a `cargo-bazel` binary
337    Returns:
338        A function that can be called to execute cargo_bazel.
339    """
340    cargo_path, rustc_path = _get_host_cargo_rustc(module_ctx)
341
342    # Placing this as a nested function allows users to call this right at the
343    # start of a module extension, thus triggering any restarts as early as
344    # possible (since module_ctx.path triggers restarts).
345    def run(args, env = {}, timeout = 600):
346        final_args = [cargo_bazel]
347        final_args.extend(args)
348        final_args.extend([
349            "--cargo",
350            cargo_path,
351            "--rustc",
352            rustc_path,
353        ])
354        result = module_ctx.execute(
355            final_args,
356            environment = dict(CARGO = cargo_path, RUSTC = rustc_path, **env),
357            timeout = timeout,
358        )
359        if result.return_code != 0:
360            if result.stdout:
361                print("Stdout:", result.stdout)  # buildifier: disable=print
362            pretty_args = " ".join([str(arg) for arg in final_args])
363            fail("%s returned with exit code %d:\n%s" % (pretty_args, result.return_code, result.stderr))
364        return result
365
366    return run
367
368def _crate_impl(module_ctx):
369    # Preload all external repositories. Calling `module_ctx.path` will cause restarts of the implementation
370    # function of the module extension, so we want to trigger all restarts before we start the actual work.
371    # Once https://github.com/bazelbuild/bazel/issues/22729 has been fixed, this code can be removed.
372    _get_host_cargo_rustc(module_ctx)
373    for mod in module_ctx.modules:
374        for cfg in mod.tags.from_cargo:
375            module_ctx.path(cfg.cargo_lockfile)
376            for m in cfg.manifests:
377                module_ctx.path(m)
378
379    cargo_bazel_output = _get_generator(module_ctx)
380    cargo_bazel = _get_cargo_bazel_runner(module_ctx, cargo_bazel_output)
381
382    all_repos = []
383    reproducible = True
384
385    for mod in module_ctx.modules:
386        module_annotations = {}
387        repo_specific_annotations = {}
388        for annotation_tag in mod.tags.annotation:
389            annotation_dict = structs.to_dict(annotation_tag)
390            repositories = annotation_dict.pop("repositories")
391            crate = annotation_dict.pop("crate")
392
393            # The crate.annotation function can take in either a list or a bool.
394            # For the tag-based method, because it has type safety, we have to
395            # split it into two parameters.
396            if annotation_dict.pop("gen_all_binaries"):
397                annotation_dict["gen_binaries"] = True
398            annotation_dict["gen_build_script"] = _OPT_BOOL_VALUES[annotation_dict["gen_build_script"]]
399
400            # Process the override targets for the annotation.
401            # In the non-bzlmod approach, this is given as a dict
402            # with the possible keys "`proc_macro`, `build_script`, `lib`, `bin`".
403            # With the tag-based approach used in Bzlmod, we run into an issue
404            # where there is no dict type that takes a string as a key and a Label as the value.
405            # To work around this, we split the override option into four, and reconstruct the
406            # dictionary here during processing
407            annotation_dict["override_targets"] = dict()
408            replacement = annotation_dict.pop("override_target_lib")
409            if replacement:
410                annotation_dict["override_targets"]["lib"] = str(replacement)
411
412            replacement = annotation_dict.pop("override_target_proc_macro")
413            if replacement:
414                annotation_dict["override_targets"]["proc_macro"] = str(replacement)
415
416            replacement = annotation_dict.pop("override_target_build_script")
417            if replacement:
418                annotation_dict["override_targets"]["build_script"] = str(replacement)
419
420            replacement = annotation_dict.pop("override_target_bin")
421            if replacement:
422                annotation_dict["override_targets"]["bin"] = str(replacement)
423
424            annotation = _crate_universe_crate.annotation(**{
425                k: v
426                for k, v in annotation_dict.items()
427                # Tag classes can't take in None, but the function requires None
428                # instead of the empty values in many cases.
429                # https://github.com/bazelbuild/bazel/issues/20744
430                if v != "" and v != [] and v != {}
431            })
432            if not repositories:
433                _get_or_insert(module_annotations, crate, []).append(annotation)
434            for repo in repositories:
435                _get_or_insert(
436                    _get_or_insert(repo_specific_annotations, repo, {}),
437                    crate,
438                    [],
439                ).append(annotation)
440
441        local_repos = []
442
443        for cfg in mod.tags.from_cargo + mod.tags.from_specs:
444            if cfg.name in local_repos:
445                fail("Defined two crate universes with the same name in the same MODULE.bazel file. Use the name tag to give them different names.")
446            elif cfg.name in all_repos:
447                fail("Defined two crate universes with the same name in different MODULE.bazel files. Either give one a different name, or use use_extension(isolate=True)")
448            all_repos.append(cfg.name)
449            local_repos.append(cfg.name)
450
451        for cfg in mod.tags.from_cargo:
452            annotations = _annotations_for_repo(
453                module_annotations,
454                repo_specific_annotations.get(cfg.name),
455            )
456
457            cargo_lockfile = module_ctx.path(cfg.cargo_lockfile)
458            manifests = {str(module_ctx.path(m)): str(m) for m in cfg.manifests}
459            _generate_hub_and_spokes(
460                module_ctx = module_ctx,
461                cargo_bazel = cargo_bazel,
462                cfg = cfg,
463                annotations = annotations,
464                cargo_lockfile = cargo_lockfile,
465                manifests = manifests,
466            )
467
468        for cfg in mod.tags.from_specs:
469            # We don't have a Cargo.lock so the resolution can change.
470            # We could maybe make this reproducible by using `-minimal-version` during resolution.
471            # See https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#minimal-versions
472            reproducible = False
473
474            annotations = _annotations_for_repo(
475                module_annotations,
476                repo_specific_annotations.get(cfg.name),
477            )
478
479            packages = {p.package: _package_to_json(p) for p in mod.tags.spec}
480            _generate_hub_and_spokes(
481                module_ctx = module_ctx,
482                cargo_bazel = cargo_bazel,
483                cfg = cfg,
484                annotations = annotations,
485                packages = packages,
486            )
487
488        for repo in repo_specific_annotations:
489            if repo not in local_repos:
490                fail("Annotation specified for repo %s, but the module defined repositories %s" % (repo, local_repos))
491
492    metadata_kwargs = {}
493    if bazel_features.external_deps.extension_metadata_has_reproducible:
494        metadata_kwargs["reproducible"] = reproducible
495
496    return module_ctx.extension_metadata(**metadata_kwargs)
497
498_from_cargo = tag_class(
499    doc = "Generates a repo @crates from a Cargo.toml / Cargo.lock pair.",
500    # Ordering is controlled for readability in generated docs.
501    attrs = {
502        "name": attr.string(
503            doc = "The name of the repo to generate",
504            default = "crates",
505        ),
506    } | {
507        "manifests": CRATES_VENDOR_ATTRS["manifests"],
508    } | {
509        "cargo_config": CRATES_VENDOR_ATTRS["cargo_config"],
510        "cargo_lockfile": CRATES_VENDOR_ATTRS["cargo_lockfile"],
511        "generate_binaries": CRATES_VENDOR_ATTRS["generate_binaries"],
512        "generate_build_scripts": CRATES_VENDOR_ATTRS["generate_build_scripts"],
513        "splicing_config": CRATES_VENDOR_ATTRS["splicing_config"],
514        "supported_platform_triples": CRATES_VENDOR_ATTRS["supported_platform_triples"],
515    },
516)
517
518# This should be kept in sync with crate_universe/private/crate.bzl.
519_annotation = tag_class(
520    attrs = {
521        "additive_build_file": attr.label(
522            doc = "A file containing extra contents to write to the bottom of generated BUILD files.",
523        ),
524        "additive_build_file_content": attr.string(
525            doc = "Extra contents to write to the bottom of generated BUILD files.",
526        ),
527        "alias_rule": attr.string(
528            doc = "Alias rule to use instead of `native.alias()`.  Overrides [render_config](#render_config)'s 'default_alias_rule'.",
529        ),
530        "build_script_data": _relative_label_list(
531            doc = "A list of labels to add to a crate's `cargo_build_script::data` attribute.",
532        ),
533        "build_script_data_glob": attr.string_list(
534            doc = "A list of glob patterns to add to a crate's `cargo_build_script::data` attribute",
535        ),
536        "build_script_deps": _relative_label_list(
537            doc = "A list of labels to add to a crate's `cargo_build_script::deps` attribute.",
538        ),
539        "build_script_env": attr.string_dict(
540            doc = "Additional environment variables to set on a crate's `cargo_build_script::env` attribute.",
541        ),
542        "build_script_proc_macro_deps": _relative_label_list(
543            doc = "A list of labels to add to a crate's `cargo_build_script::proc_macro_deps` attribute.",
544        ),
545        "build_script_rundir": attr.string(
546            doc = "An override for the build script's rundir attribute.",
547        ),
548        "build_script_rustc_env": attr.string_dict(
549            doc = "Additional environment variables to set on a crate's `cargo_build_script::env` attribute.",
550        ),
551        "build_script_toolchains": attr.label_list(
552            doc = "A list of labels to set on a crates's `cargo_build_script::toolchains` attribute.",
553        ),
554        "build_script_tools": _relative_label_list(
555            doc = "A list of labels to add to a crate's `cargo_build_script::tools` attribute.",
556        ),
557        "compile_data": _relative_label_list(
558            doc = "A list of labels to add to a crate's `rust_library::compile_data` attribute.",
559        ),
560        "compile_data_glob": attr.string_list(
561            doc = "A list of glob patterns to add to a crate's `rust_library::compile_data` attribute.",
562        ),
563        "crate": attr.string(
564            doc = "The name of the crate the annotation is applied to",
565            mandatory = True,
566        ),
567        "crate_features": attr.string_list(
568            doc = "A list of strings to add to a crate's `rust_library::crate_features` attribute.",
569        ),
570        "data": _relative_label_list(
571            doc = "A list of labels to add to a crate's `rust_library::data` attribute.",
572        ),
573        "data_glob": attr.string_list(
574            doc = "A list of glob patterns to add to a crate's `rust_library::data` attribute.",
575        ),
576        "deps": _relative_label_list(
577            doc = "A list of labels to add to a crate's `rust_library::deps` attribute.",
578        ),
579        "disable_pipelining": attr.bool(
580            doc = "If True, disables pipelining for library targets for this crate.",
581        ),
582        "extra_aliased_targets": attr.string_dict(
583            doc = "A list of targets to add to the generated aliases in the root crate_universe repository.",
584        ),
585        "gen_all_binaries": attr.bool(
586            doc = "If true, generates `rust_binary` targets for all of the crates bins",
587        ),
588        "gen_binaries": attr.string_list(
589            doc = "As a list, the subset of the crate's bins that should get `rust_binary` targets produced.",
590        ),
591        "gen_build_script": attr.string(
592            doc = "An authorative flag to determine whether or not to produce `cargo_build_script` targets for the current crate. Supported values are 'on', 'off', and 'auto'.",
593            values = _OPT_BOOL_VALUES.keys(),
594            default = "auto",
595        ),
596        "override_target_bin": attr.label(
597            doc = "An optional alternate taget to use when something depends on this crate to allow the parent repo to provide its own version of this dependency.",
598        ),
599        "override_target_build_script": attr.label(
600            doc = "An optional alternate taget to use when something depends on this crate to allow the parent repo to provide its own version of this dependency.",
601        ),
602        "override_target_lib": attr.label(
603            doc = "An optional alternate taget to use when something depends on this crate to allow the parent repo to provide its own version of this dependency.",
604        ),
605        "override_target_proc_macro": attr.label(
606            doc = "An optional alternate taget to use when something depends on this crate to allow the parent repo to provide its own version of this dependency.",
607        ),
608        "patch_args": attr.string_list(
609            doc = "The `patch_args` attribute of a Bazel repository rule. See [http_archive.patch_args](https://docs.bazel.build/versions/main/repo/http.html#http_archive-patch_args)",
610        ),
611        "patch_tool": attr.string(
612            doc = "The `patch_tool` attribute of a Bazel repository rule. See [http_archive.patch_tool](https://docs.bazel.build/versions/main/repo/http.html#http_archive-patch_tool)",
613        ),
614        "patches": attr.label_list(
615            doc = "The `patches` attribute of a Bazel repository rule. See [http_archive.patches](https://docs.bazel.build/versions/main/repo/http.html#http_archive-patches)",
616        ),
617        "proc_macro_deps": _relative_label_list(
618            doc = "A list of labels to add to a crate's `rust_library::proc_macro_deps` attribute.",
619        ),
620        "repositories": attr.string_list(
621            doc = "A list of repository names specified from `crate.from_cargo(name=...)` that this annotation is applied to. Defaults to all repositories.",
622            default = [],
623        ),
624        "rustc_env": attr.string_dict(
625            doc = "Additional variables to set on a crate's `rust_library::rustc_env` attribute.",
626        ),
627        "rustc_env_files": _relative_label_list(
628            doc = "A list of labels to set on a crate's `rust_library::rustc_env_files` attribute.",
629        ),
630        "rustc_flags": attr.string_list(
631            doc = "A list of strings to set on a crate's `rust_library::rustc_flags` attribute.",
632        ),
633        "shallow_since": attr.string(
634            doc = "An optional timestamp used for crates originating from a git repository instead of a crate registry. This flag optimizes fetching the source code.",
635        ),
636        "version": attr.string(
637            doc = "The versions of the crate the annotation is applied to. Defaults to all versions.",
638            default = "*",
639        ),
640    },
641)
642
643_from_specs = tag_class(
644    doc = "Generates a repo @crates from the defined `spec` tags.",
645    attrs = {
646        "name": attr.string(
647            doc = "The name of the repo to generate.",
648            default = "crates",
649        ),
650    } | {
651        "cargo_config": CRATES_VENDOR_ATTRS["cargo_config"],
652        "generate_binaries": CRATES_VENDOR_ATTRS["generate_binaries"],
653        "generate_build_scripts": CRATES_VENDOR_ATTRS["generate_build_scripts"],
654        "splicing_config": CRATES_VENDOR_ATTRS["splicing_config"],
655        "supported_platform_triples": CRATES_VENDOR_ATTRS["supported_platform_triples"],
656    },
657)
658
659# This should be kept in sync with crate_universe/private/crate.bzl.
660_spec = tag_class(
661    attrs = {
662        "artifact": attr.string(
663            doc = "Set to 'bin' to pull in a binary crate as an artifact dependency. Requires a nightly Cargo.",
664        ),
665        "branch": attr.string(
666            doc = "The git branch of the remote crate. Tied with the `git` param. Only one of branch, tag or rev may be specified. Specifying `rev` is recommended for fully-reproducible builds.",
667        ),
668        "default_features": attr.bool(
669            doc = "Maps to the `default-features` flag.",
670            default = True,
671        ),
672        "features": attr.string_list(
673            doc = "A list of features to use for the crate.",
674        ),
675        "git": attr.string(
676            doc = "The Git url to use for the crate. Cannot be used with `version`.",
677        ),
678        "lib": attr.bool(
679            doc = "If using `artifact = 'bin'`, additionally setting `lib = True` declares a dependency on both the package's library and binary, as opposed to just the binary.",
680        ),
681        "package": attr.string(
682            doc = "The explicit name of the package.",
683            mandatory = True,
684        ),
685        "rev": attr.string(
686            doc = "The git revision of the remote crate. Tied with the `git` param. Only one of branch, tag or rev may be specified.",
687        ),
688        "tag": attr.string(
689            doc = "The git tag of the remote crate. Tied with the `git` param. Only one of branch, tag or rev may be specified. Specifying `rev` is recommended for fully-reproducible builds.",
690        ),
691        "version": attr.string(
692            doc = "The exact version of the crate. Cannot be used with `git`.",
693        ),
694    },
695)
696
697_conditional_crate_args = {
698    "arch_dependent": True,
699    "os_dependent": True,
700} if bazel_features.external_deps.module_extension_has_os_arch_dependent else {}
701
702crate = module_extension(
703    doc = "Crate universe module extensions.",
704    implementation = _crate_impl,
705    tag_classes = {
706        "annotation": _annotation,
707        "from_cargo": _from_cargo,
708        "from_specs": _from_specs,
709        "spec": _spec,
710    },
711    **_conditional_crate_args
712)