fork/rules_rust

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

Xùdōng YángStrip leading '@'s for labels in the splicing manifest (#1547)6dacd980

0.11.0
6.5 KiB191 linesraw
1"""Utilities directly related to the `splicing` step of `cargo-bazel`."""
2
3load(":common_utils.bzl", "CARGO_BAZEL_REPIN", "REPIN", "cargo_environ", "execute")
4
5CARGO_BAZEL_DEBUG = "CARGO_BAZEL_DEBUG"
6
7def splicing_config(resolver_version = "1"):
8    """Various settings used to configure Cargo manifest splicing behavior.
9
10    [rv]: https://doc.rust-lang.org/cargo/reference/resolver.html#resolver-versions
11
12    Args:
13        resolver_version (str, optional): The [resolver version][rv] to use in generated Cargo
14            manifests. This flag is **only** used when splicing a manifest from direct package
15            definitions. See `crates_repository::packages`.
16
17    Returns:
18        str: A json encoded string of the parameters provided
19    """
20    return json.encode(struct(
21        resolver_version = resolver_version,
22    ))
23
24def kebab_case_keys(data):
25    """Ensure the key value of the data given are kebab-case
26
27    Args:
28        data (dict): A deserialized json blob
29
30    Returns:
31        dict: The same `data` but with kebab-case keys
32    """
33    return {
34        key.lower().replace("_", "-"): val
35        for (key, val) in data.items()
36    }
37
38def compile_splicing_manifest(splicing_config, manifests, cargo_config_path, packages):
39    """Produce a manifest containing required components for splciing a new Cargo workspace
40
41    [cargo_config]: https://doc.rust-lang.org/cargo/reference/config.html
42    [cargo_toml]: https://doc.rust-lang.org/cargo/reference/manifest.html
43
44    Args:
45        splicing_config (dict): A deserialized `splicing_config`
46        manifests (dict): A mapping of paths to Bazel labels which represent [Cargo manifests][cargo_toml].
47        cargo_config_path (str): The absolute path to a [Cargo config][cargo_config].
48        packages (dict): A set of crates (packages) specifications to depend on
49
50    Returns:
51        dict: A dictionary representation of a `cargo_bazel::splicing::SplicingManifest`
52    """
53
54    # Deserialize information about direct packges
55    direct_packages_info = {
56        # Ensure the data is using kebab-case as that's what `cargo_toml::DependencyDetail` expects.
57        pkg: kebab_case_keys(dict(json.decode(data)))
58        for (pkg, data) in packages.items()
59    }
60
61    # Auto-generated splicier manifest values
62    splicing_manifest_content = {
63        "cargo_config": cargo_config_path,
64        "direct_packages": direct_packages_info,
65        "manifests": manifests,
66    }
67
68    return dict(splicing_config.items() + splicing_manifest_content.items())
69
70def _no_at_label(label):
71    """Strips leading '@'s for stringified labels in the main repository for backwards-comaptibility reasons."""
72    s = str(label)
73    if s.startswith("@@//"):
74        return s[2:]
75    if s.startswith("@//"):
76        return s[1:]
77    return s
78
79def create_splicing_manifest(repository_ctx):
80    """Produce a manifest containing required components for splciing a new Cargo workspace
81
82    Args:
83        repository_ctx (repository_ctx): The rule's context object.
84
85    Returns:
86        path: The path to a json encoded manifest
87    """
88
89    manifests = {str(repository_ctx.path(m)): _no_at_label(m) for m in repository_ctx.attr.manifests}
90
91    if repository_ctx.attr.cargo_config:
92        cargo_config = str(repository_ctx.path(repository_ctx.attr.cargo_config))
93    else:
94        cargo_config = None
95
96    # Load user configurable splicing settings
97    config = json.decode(repository_ctx.attr.splicing_config or splicing_config())
98
99    repo_dir = repository_ctx.path(".")
100
101    splicing_manifest = repository_ctx.path("{}/splicing_manifest.json".format(repo_dir))
102
103    data = compile_splicing_manifest(
104        splicing_config = config,
105        manifests = manifests,
106        cargo_config_path = cargo_config,
107        packages = repository_ctx.attr.packages,
108    )
109
110    # Serialize information required for splicing
111    repository_ctx.file(
112        splicing_manifest,
113        json.encode_indent(
114            data,
115            indent = " " * 4,
116        ),
117    )
118
119    return splicing_manifest
120
121def splice_workspace_manifest(repository_ctx, generator, cargo_lockfile, splicing_manifest, cargo, rustc):
122    """Splice together a Cargo workspace from various other manifests and package definitions
123
124    Args:
125        repository_ctx (repository_ctx): The rule's context object.
126        generator (path): The `cargo-bazel` binary.
127        cargo_lockfile (path): The path to a "Cargo.lock" file.
128        splicing_manifest (path): The path to a splicing manifest.
129        cargo (path): The path to a Cargo binary.
130        rustc (path): The Path to a Rustc binary.
131
132    Returns:
133        path: The path to a Cargo metadata json file found in the spliced workspace root.
134    """
135    repository_ctx.report_progress("Splicing Cargo workspace.")
136    repo_dir = repository_ctx.path(".")
137
138    splicing_output_dir = repository_ctx.path("splicing-output")
139
140    # Generate a workspace root which contains all workspace members
141    arguments = [
142        generator,
143        "splice",
144        "--output-dir",
145        splicing_output_dir,
146        "--splicing-manifest",
147        splicing_manifest,
148        "--cargo",
149        cargo,
150        "--rustc",
151        rustc,
152        "--cargo-lockfile",
153        cargo_lockfile,
154    ]
155
156    # Optionally set the splicing workspace directory to somewhere within the repository directory
157    # to improve the debugging experience.
158    if CARGO_BAZEL_DEBUG in repository_ctx.os.environ:
159        arguments.extend([
160            "--workspace-dir",
161            repository_ctx.path("{}/splicing-workspace".format(repo_dir)),
162        ])
163
164    env = {
165        "CARGO": str(cargo),
166        "RUSTC": str(rustc),
167        "RUST_BACKTRACE": "full",
168    }
169
170    # Ensure the short hand repin variable is set to the full name.
171    if REPIN in repository_ctx.os.environ and CARGO_BAZEL_REPIN not in repository_ctx.os.environ:
172        env.update({CARGO_BAZEL_REPIN: repository_ctx.os.environ[REPIN]})
173
174    # Add any Cargo environment variables to the `cargo-bazel` execution
175    env.update(cargo_environ(repository_ctx))
176
177    execute(
178        repository_ctx = repository_ctx,
179        args = arguments,
180        env = env,
181    )
182
183    # This file must have been produced by the execution above.
184    spliced_lockfile = repository_ctx.path("{}/Cargo.lock".format(splicing_output_dir))
185    if not spliced_lockfile.exists:
186        fail("Lockfile file does not exist: {}".format(spliced_lockfile))
187    spliced_metadata = repository_ctx.path("{}/metadata.json".format(splicing_output_dir))
188    if not spliced_metadata.exists:
189        fail("Metadata file does not exist: {}".format(spliced_metadata))
190
191    return spliced_metadata