Squashed 'third_party/rules_rust/' content from commit bf59038ca

git-subtree-dir: third_party/rules_rust
git-subtree-split: bf59038cac11798cbaef9f3bf965bad8182b97fa
Signed-off-by: Brian Silverman <bsilver16384@gmail.com>
Change-Id: I5a20e403203d670df467ea97dde9a4ac40339a8d
diff --git a/crate_universe/src/rendering/template_engine.rs b/crate_universe/src/rendering/template_engine.rs
new file mode 100644
index 0000000..792802f
--- /dev/null
+++ b/crate_universe/src/rendering/template_engine.rs
@@ -0,0 +1,399 @@
+//! A template engine backed by [Tera] for rendering Files.
+
+use std::collections::HashMap;
+
+use anyhow::{Context as AnyhowContext, Result};
+use serde_json::{from_value, to_value, Value};
+use tera::{self, Tera};
+
+use crate::config::{CrateId, RenderConfig};
+use crate::context::Context;
+use crate::rendering::{
+    render_crate_bazel_label, render_crate_bazel_repository, render_crate_build_file,
+    render_module_label, render_platform_constraint_label,
+};
+use crate::utils::sanitize_module_name;
+use crate::utils::sanitize_repository_name;
+use crate::utils::starlark::{SelectStringDict, SelectStringList};
+
+pub struct TemplateEngine {
+    engine: Tera,
+    context: tera::Context,
+}
+
+impl TemplateEngine {
+    pub fn new(render_config: &RenderConfig) -> Self {
+        let mut tera = Tera::default();
+        tera.add_raw_templates(vec![
+            (
+                "partials/crate/aliases.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/crate/aliases.j2"
+                )),
+            ),
+            (
+                "partials/crate/binary.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/crate/binary.j2"
+                )),
+            ),
+            (
+                "partials/crate/build_script.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/crate/build_script.j2"
+                )),
+            ),
+            (
+                "partials/crate/common_attrs.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/crate/common_attrs.j2"
+                )),
+            ),
+            (
+                "partials/crate/deps.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/crate/deps.j2"
+                )),
+            ),
+            (
+                "partials/crate/library.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/crate/library.j2"
+                )),
+            ),
+            (
+                "partials/crate/proc_macro.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/crate/proc_macro.j2"
+                )),
+            ),
+            (
+                "partials/module/aliases_map.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/module/aliases_map.j2"
+                )),
+            ),
+            (
+                "partials/module/deps_map.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/module/deps_map.j2"
+                )),
+            ),
+            (
+                "partials/module/repo_git.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/module/repo_git.j2"
+                )),
+            ),
+            (
+                "partials/module/repo_http.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/module/repo_http.j2"
+                )),
+            ),
+            (
+                "partials/starlark/glob.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/starlark/glob.j2"
+                )),
+            ),
+            (
+                "partials/starlark/selectable_dict.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/starlark/selectable_dict.j2"
+                )),
+            ),
+            (
+                "partials/starlark/selectable_list.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/starlark/selectable_list.j2"
+                )),
+            ),
+            (
+                "partials/header.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/partials/header.j2"
+                )),
+            ),
+            (
+                "crate_build_file.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/crate_build_file.j2"
+                )),
+            ),
+            (
+                "module_build_file.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/module_build_file.j2"
+                )),
+            ),
+            (
+                "module_bzl.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/module_bzl.j2"
+                )),
+            ),
+            (
+                "vendor_module.j2",
+                include_str!(concat!(
+                    env!("CARGO_MANIFEST_DIR"),
+                    "/src/rendering/templates/vendor_module.j2"
+                )),
+            ),
+        ])
+        .unwrap();
+
+        tera.register_function(
+            "crate_build_file",
+            crate_build_file_fn_generator(render_config.build_file_template.clone()),
+        );
+        tera.register_function(
+            "crate_label",
+            crate_label_fn_generator(
+                render_config.crate_label_template.clone(),
+                render_config.repository_name.clone(),
+            ),
+        );
+        tera.register_function(
+            "crate_repository",
+            crate_repository_fn_generator(
+                render_config.crate_repository_template.clone(),
+                render_config.repository_name.clone(),
+            ),
+        );
+        tera.register_function(
+            "platform_label",
+            platform_label_fn_generator(render_config.platforms_template.clone()),
+        );
+        tera.register_function("sanitize_module_name", sanitize_module_name_fn);
+        tera.register_function(
+            "crates_module_label",
+            module_label_fn_generator(render_config.crates_module_template.clone()),
+        );
+
+        let mut context = tera::Context::new();
+        context.insert("default_select_list", &SelectStringList::default());
+        context.insert("default_select_dict", &SelectStringDict::default());
+        context.insert("repository_name", &render_config.repository_name);
+        context.insert("vendor_mode", &render_config.vendor_mode);
+        context.insert("Null", &tera::Value::Null);
+        context.insert(
+            "default_package_name",
+            &match render_config.default_package_name.as_ref() {
+                Some(pkg_name) => format!("\"{}\"", pkg_name),
+                None => "None".to_owned(),
+            },
+        );
+
+        Self {
+            engine: tera,
+            context,
+        }
+    }
+
+    fn new_tera_ctx(&self) -> tera::Context {
+        self.context.clone()
+    }
+
+    pub fn render_crate_build_files<'a>(
+        &self,
+        ctx: &'a Context,
+    ) -> Result<HashMap<&'a CrateId, String>> {
+        // Create the render context with the global planned context to be
+        // reused when rendering crates.
+        let mut context = self.new_tera_ctx();
+        context.insert("context", ctx);
+
+        ctx.crates
+            .iter()
+            .map(|(id, _)| {
+                let aliases = ctx.crate_aliases(id, false, false);
+                let build_aliases = ctx.crate_aliases(id, true, false);
+
+                context.insert("crate_id", &id);
+                context.insert("common_aliases", &aliases);
+                context.insert("build_aliases", &build_aliases);
+
+                let content = self
+                    .engine
+                    .render("crate_build_file.j2", &context)
+                    .context("Failed to render BUILD file")?;
+
+                Ok((id, content))
+            })
+            .collect()
+    }
+
+    pub fn render_module_build_file(&self, data: &Context) -> Result<String> {
+        let mut context = self.new_tera_ctx();
+        context.insert("context", data);
+
+        let workspace_member_deps = data.flat_workspace_member_deps();
+        context.insert("workspace_member_dependencies", &workspace_member_deps);
+
+        let binary_crates_map = data.flat_binary_deps();
+        context.insert("binary_crates_map", &binary_crates_map);
+
+        self.engine
+            .render("module_build_file.j2", &context)
+            .context("Failed to render crates module")
+    }
+
+    pub fn render_module_bzl(&self, data: &Context) -> Result<String> {
+        let mut context = self.new_tera_ctx();
+        context.insert("context", data);
+
+        self.engine
+            .render("module_bzl.j2", &context)
+            .context("Failed to render crates module")
+    }
+
+    pub fn render_vendor_module_file(&self, data: &Context) -> Result<String> {
+        let mut context = self.new_tera_ctx();
+        context.insert("context", data);
+
+        self.engine
+            .render("vendor_module.j2", &context)
+            .context("Failed to render vendor module")
+    }
+}
+
+/// A convienience wrapper for parsing parameters to tera functions
+macro_rules! parse_tera_param {
+    ($param:literal, $param_type:ty, $args:ident) => {
+        match $args.get($param) {
+            Some(val) => match from_value::<$param_type>(val.clone()) {
+                Ok(v) => v,
+                Err(_) => {
+                    return Err(tera::Error::msg(format!(
+                        "The `{}` paramater could not be parsed as a String.",
+                        $param
+                    )))
+                }
+            },
+            None => {
+                return Err(tera::Error::msg(format!(
+                    "No `{}` parameter was passed.",
+                    $param
+                )))
+            }
+        }
+    };
+}
+
+/// Convert a crate name into a module name by applying transforms to invalid characters.
+fn sanitize_module_name_fn(args: &HashMap<String, Value>) -> tera::Result<Value> {
+    let crate_name = parse_tera_param!("crate_name", String, args);
+
+    match to_value(sanitize_module_name(&crate_name)) {
+        Ok(v) => Ok(v),
+        Err(_) => Err(tera::Error::msg("Failed to generate resulting module name")),
+    }
+}
+
+/// Convert a crate name into a module name by applying transforms to invalid characters.
+fn platform_label_fn_generator(template: String) -> impl tera::Function {
+    Box::new(
+        move |args: &HashMap<String, Value>| -> tera::Result<Value> {
+            let triple = parse_tera_param!("triple", String, args);
+            match to_value(render_platform_constraint_label(&template, &triple)) {
+                Ok(v) => Ok(v),
+                Err(_) => Err(tera::Error::msg("Failed to generate resulting module name")),
+            }
+        },
+    )
+}
+
+/// Convert a crate name into a module name by applying transforms to invalid characters.
+fn crate_build_file_fn_generator(template: String) -> impl tera::Function {
+    Box::new(
+        move |args: &HashMap<String, Value>| -> tera::Result<Value> {
+            let name = parse_tera_param!("name", String, args);
+            let version = parse_tera_param!("version", String, args);
+
+            match to_value(render_crate_build_file(&template, &name, &version)) {
+                Ok(v) => Ok(v),
+                Err(_) => Err(tera::Error::msg("Failed to generate crate's BUILD file")),
+            }
+        },
+    )
+}
+
+/// Convert a file name to a Bazel label
+fn module_label_fn_generator(template: String) -> impl tera::Function {
+    Box::new(
+        move |args: &HashMap<String, Value>| -> tera::Result<Value> {
+            let file = parse_tera_param!("file", String, args);
+
+            let label = match render_module_label(&template, &file) {
+                Ok(v) => v,
+                Err(e) => return Err(tera::Error::msg(e)),
+            };
+
+            match to_value(label.to_string()) {
+                Ok(v) => Ok(v),
+                Err(_) => Err(tera::Error::msg("Failed to generate crate's BUILD file")),
+            }
+        },
+    )
+}
+
+/// Convert a crate name into a module name by applying transforms to invalid characters.
+fn crate_label_fn_generator(template: String, repository_name: String) -> impl tera::Function {
+    Box::new(
+        move |args: &HashMap<String, Value>| -> tera::Result<Value> {
+            let name = parse_tera_param!("name", String, args);
+            let version = parse_tera_param!("version", String, args);
+            let target = parse_tera_param!("target", String, args);
+
+            match to_value(sanitize_repository_name(&render_crate_bazel_label(
+                &template,
+                &repository_name,
+                &name,
+                &version,
+                &target,
+            ))) {
+                Ok(v) => Ok(v),
+                Err(_) => Err(tera::Error::msg("Failed to generate crate's label")),
+            }
+        },
+    )
+}
+
+/// Convert a crate name into a module name by applying transforms to invalid characters.
+fn crate_repository_fn_generator(template: String, repository_name: String) -> impl tera::Function {
+    Box::new(
+        move |args: &HashMap<String, Value>| -> tera::Result<Value> {
+            let name = parse_tera_param!("name", String, args);
+            let version = parse_tera_param!("version", String, args);
+
+            match to_value(sanitize_repository_name(&render_crate_bazel_repository(
+                &template,
+                &repository_name,
+                &name,
+                &version,
+            ))) {
+                Ok(v) => Ok(v),
+                Err(_) => Err(tera::Error::msg("Failed to generate crate repository name")),
+            }
+        },
+    )
+}
diff --git a/crate_universe/src/rendering/templates/crate_build_file.j2 b/crate_universe/src/rendering/templates/crate_build_file.j2
new file mode 100644
index 0000000..ff9d4ad
--- /dev/null
+++ b/crate_universe/src/rendering/templates/crate_build_file.j2
@@ -0,0 +1,44 @@
+{%- set crate = context.crates | get(key=crate_id) %}
+{%- include "partials/header.j2" %}
+
+load(
+    "@bazel_skylib//lib:selects.bzl", 
+    "selects",
+)
+load(
+    "@rules_rust//cargo:defs.bzl",
+    "cargo_build_script",
+)
+load(
+    "@rules_rust//rust:defs.bzl",
+    "rust_binary",
+    "rust_library",
+    "rust_proc_macro",
+)
+
+# buildifier: disable=bzl-visibility
+load("@rules_rust//crate_universe/private:selects.bzl", "select_with_or")
+
+package(default_visibility = ["//visibility:public"])
+
+# licenses([
+#     "TODO",  # {{ crate.license }}
+# ])
+
+{% for rule in crate.targets -%}
+{%- for rule_type, target in rule %}
+{%- if rule_type in ["BuildScript"] %}
+{% include "partials/crate/build_script.j2" %}
+{%- elif rule_type in ["ProcMacro"] %}
+{% include "partials/crate/proc_macro.j2" %}
+{%- elif rule_type in ["Library"] %}
+{% include "partials/crate/library.j2" %}
+{%- elif rule_type in ["Binary"] %}
+{% include "partials/crate/binary.j2" %}
+{%- endif %}
+{%- endfor %}
+{%- endfor %}
+{%- if crate.additive_build_file_content %}
+# Additive BUILD file content
+{{ crate.additive_build_file_content }}
+{%- endif %}
diff --git a/crate_universe/src/rendering/templates/module_build_file.j2 b/crate_universe/src/rendering/templates/module_build_file.j2
new file mode 100644
index 0000000..63124dc
--- /dev/null
+++ b/crate_universe/src/rendering/templates/module_build_file.j2
@@ -0,0 +1,49 @@
+{%- include "partials/header.j2" %}
+
+package(default_visibility = ["//visibility:public"])
+
+exports_files(
+    [
+        "cargo-bazel.json",
+        "defs.bzl",
+        {%- set current_vendor_mode = vendor_mode | default(value="") %}{%- if current_vendor_mode == "remote" %}"crates.bzl",{%- endif %}
+    ] + glob([
+        "*.bazel",
+    ]),
+)
+
+filegroup(
+    name = "srcs",
+    srcs = glob([
+        "*.bazel",
+        "*.bzl",
+    ]),
+)
+
+# Workspace Member Dependencies
+{%- for dep, rename in workspace_member_dependencies %}
+{%- set crate = context.crates | get(key=dep) %}
+{%- if crate | get(key="library_target_name", default=Null) %}
+alias(
+    name = "{{ rename | default(value=crate.name) }}",
+    actual = "{{ crate_label(name = crate.name, version = crate.version, target = crate.library_target_name) }}",
+    tags = ["manual"],
+)
+{%- endif %}
+{%- endfor %}
+
+# Binaries
+{%- for id, rename in binary_crates_map %}
+{%- set crate = context.crates | get(key=id) %}
+{%- for rule in crate.targets %}
+{%- for rule_type, target in rule %}
+{%- if rule_type in ["Binary"] %}
+alias(
+    name = "{{ rename | default(value=crate.name) }}__{{ target.crate_name }}",
+    actual = "{{ crate_label(name = crate.name, version = crate.version, target = target.crate_name ~ '__bin') }}",
+    tags = ["manual"],
+)
+{%- endif %}
+{%- endfor %}
+{%- endfor %}
+{%- endfor %}
diff --git a/crate_universe/src/rendering/templates/module_bzl.j2 b/crate_universe/src/rendering/templates/module_bzl.j2
new file mode 100644
index 0000000..4ea1624
--- /dev/null
+++ b/crate_universe/src/rendering/templates/module_bzl.j2
@@ -0,0 +1,338 @@
+{#
+To keep line numbers consistent with the rendered version, empty space is
+intentionally plced here which should match the line length of `partials/header.j2`.
+
+Expected length = 6 lines
+#}{%- include "partials/header.j2" %}
+"""
+# `crates_repository` API
+
+- [aliases](#aliases)
+- [crate_deps](#crate_deps)
+- [all_crate_deps](#all_crate_deps)
+- [crate_repositories](#crate_repositories)
+
+"""
+
+load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository")
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
+load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
+load("@bazel_skylib//lib:selects.bzl", "selects")
+
+###############################################################################
+# MACROS API
+###############################################################################
+
+# An identifier that represent common dependencies (unconditional).
+_COMMON_CONDITION = ""
+
+def _flatten_dependency_maps(all_dependency_maps):
+    """Flatten a list of dependency maps into one dictionary.
+
+    Dependency maps have the following structure:
+
+    ```python
+    DEPENDENCIES_MAP = {
+        # The first key in the map is a Bazel package
+        # name of the workspace this file is defined in.
+        "workspace_member_package": {
+
+            # Not all dependnecies are supported for all platforms.
+            # the condition key is the condition required to be true
+            # on the host platform.
+            "condition": {
+
+                # An alias to a crate target.     # The label of the crate target the
+                # Aliases are only crate names.   # package name refers to.
+                "package_name":                   "@full//:label",
+            }
+        }
+    }
+    ```
+
+    Args:
+        all_dependency_maps (list): A list of dicts as described above
+
+    Returns:
+        dict: A dictionary as described above
+    """
+    dependencies = {}
+
+    for workspace_deps_map in all_dependency_maps:
+        for pkg_name, conditional_deps_map in workspace_deps_map.items():
+            if pkg_name not in dependencies:
+                non_frozen_map = dict()
+                for key, values in conditional_deps_map.items():
+                    non_frozen_map.update({key: dict(values.items())})
+                dependencies.setdefault(pkg_name, non_frozen_map)
+                continue
+
+            for condition, deps_map in conditional_deps_map.items():
+                # If the condition has not been recorded, do so and continue
+                if condition not in dependencies[pkg_name]:
+                    dependencies[pkg_name].setdefault(condition, dict(deps_map.items()))
+                    continue
+
+                # Alert on any miss-matched dependencies
+                inconsistent_entries = []
+                for crate_name, crate_label in deps_map.items():
+                    existing = dependencies[pkg_name][condition].get(crate_name)
+                    if existing and existing != crate_label:
+                        inconsistent_entries.append((crate_name, existing, crate_label))
+                    dependencies[pkg_name][condition].update({crate_name: crate_label})
+
+    return dependencies
+
+def crate_deps(deps, package_name = {{ default_package_name }}):
+    """Finds the fully qualified label of the requested crates for the package where this macro is called.
+
+    Args:
+        deps (list): The desired list of crate targets.
+        package_name (str, optional): The package name of the set of dependencies to look up.
+            Defaults to `native.package_name()`.
+
+    Returns:
+        list: A list of labels to generated rust targets (str)
+    """
+
+    if not deps:
+        return []
+
+    if package_name == None:
+        package_name = native.package_name()
+
+    # Join both sets of dependencies
+    dependencies = _flatten_dependency_maps([
+        _NORMAL_DEPENDENCIES,
+        _NORMAL_DEV_DEPENDENCIES,
+        _PROC_MACRO_DEPENDENCIES,
+        _PROC_MACRO_DEV_DEPENDENCIES,
+        _BUILD_DEPENDENCIES,
+        _BUILD_PROC_MACRO_DEPENDENCIES,
+    ]).pop(package_name, {})
+
+    # Combine all conditional packages so we can easily index over a flat list
+    # TODO: Perhaps this should actually return select statements and maintain
+    # the conditionals of the dependencies
+    flat_deps = {}
+    for deps_set in dependencies.values():
+        for crate_name, crate_label in deps_set.items():
+            flat_deps.update({crate_name: crate_label})
+
+    missing_crates = []
+    crate_targets = []
+    for crate_target in deps:
+        if crate_target not in flat_deps:
+            missing_crates.append(crate_target)
+        else:
+            crate_targets.append(flat_deps[crate_target])
+
+    if missing_crates:
+        fail("Could not find crates `{}` among dependencies of `{}`. Available dependencies were `{}`".format(
+            missing_crates,
+            package_name,
+            dependencies,
+        ))
+
+    return crate_targets
+
+def all_crate_deps(
+        normal = False, 
+        normal_dev = False, 
+        proc_macro = False, 
+        proc_macro_dev = False,
+        build = False,
+        build_proc_macro = False,
+        package_name = {{ default_package_name }}):
+    """Finds the fully qualified label of all requested direct crate dependencies \
+    for the package where this macro is called.
+
+    If no parameters are set, all normal dependencies are returned. Setting any one flag will
+    otherwise impact the contents of the returned list.
+
+    Args:
+        normal (bool, optional): If True, normal dependencies are included in the
+            output list.
+        normal_dev (bool, optional): If True, normla dev dependencies will be
+            included in the output list..
+        proc_macro (bool, optional): If True, proc_macro dependencies are included
+            in the output list.
+        proc_macro_dev (bool, optional): If True, dev proc_macro dependencies are
+            included in the output list.
+        build (bool, optional): If True, build dependencies are included
+            in the output list.
+        build_proc_macro (bool, optional): If True, build proc_macro dependencies are
+            included in the output list.
+        package_name (str, optional): The package name of the set of dependencies to look up.
+            Defaults to `native.package_name()` when unset.
+
+    Returns:
+        list: A list of labels to generated rust targets (str)
+    """
+
+    if package_name == None:
+        package_name = native.package_name()
+
+    # Determine the relevant maps to use
+    all_dependency_maps = []
+    if normal:
+        all_dependency_maps.append(_NORMAL_DEPENDENCIES)
+    if normal_dev:
+        all_dependency_maps.append(_NORMAL_DEV_DEPENDENCIES)
+    if proc_macro:
+        all_dependency_maps.append(_PROC_MACRO_DEPENDENCIES)
+    if proc_macro_dev:
+        all_dependency_maps.append(_PROC_MACRO_DEV_DEPENDENCIES)
+    if build:
+        all_dependency_maps.append(_BUILD_DEPENDENCIES)
+    if build_proc_macro:
+        all_dependency_maps.append(_BUILD_PROC_MACRO_DEPENDENCIES)
+
+    # Default to always using normal dependencies
+    if not all_dependency_maps:
+        all_dependency_maps.append(_NORMAL_DEPENDENCIES)
+
+    dependencies = _flatten_dependency_maps(all_dependency_maps).pop(package_name, None)
+
+    if not dependencies:
+        return []
+
+    crate_deps = list(dependencies.pop(_COMMON_CONDITION, {}).values())
+    for condition, deps in dependencies.items():
+        crate_deps += selects.with_or({_CONDITIONS[condition]: deps.values()})
+
+    return crate_deps
+
+def aliases(
+        normal = False,
+        normal_dev = False,
+        proc_macro = False,
+        proc_macro_dev = False,
+        build = False,
+        build_proc_macro = False,
+        package_name = {{ default_package_name }}):
+    """Produces a map of Crate alias names to their original label
+
+    If no dependency kinds are specified, `normal` and `proc_macro` are used by default.
+    Setting any one flag will otherwise determine the contents of the returned dict.
+
+    Args:
+        normal (bool, optional): If True, normal dependencies are included in the
+            output list.
+        normal_dev (bool, optional): If True, normla dev dependencies will be
+            included in the output list..
+        proc_macro (bool, optional): If True, proc_macro dependencies are included
+            in the output list.
+        proc_macro_dev (bool, optional): If True, dev proc_macro dependencies are
+            included in the output list.
+        build (bool, optional): If True, build dependencies are included
+            in the output list.
+        build_proc_macro (bool, optional): If True, build proc_macro dependencies are
+            included in the output list.
+        package_name (str, optional): The package name of the set of dependencies to look up.
+            Defaults to `native.package_name()` when unset.
+
+    Returns:
+        dict: The aliases of all associated packages
+    """
+    if package_name == None:
+        package_name = native.package_name()
+
+    # Determine the relevant maps to use
+    all_aliases_maps = []
+    if normal:
+        all_aliases_maps.append(_NORMAL_ALIASES)
+    if normal_dev:
+        all_aliases_maps.append(_NORMAL_DEV_ALIASES)
+    if proc_macro:
+        all_aliases_maps.append(_PROC_MACRO_ALIASES)
+    if proc_macro_dev:
+        all_aliases_maps.append(_PROC_MACRO_DEV_ALIASES)
+    if build:
+        all_aliases_maps.append(_BUILD_ALIASES)
+    if build_proc_macro:
+        all_aliases_maps.append(_BUILD_PROC_MACRO_ALIASES)
+
+    # Default to always using normal aliases
+    if not all_aliases_maps:
+        all_aliases_maps.append(_NORMAL_ALIASES)
+        all_aliases_maps.append(_PROC_MACRO_ALIASES)
+
+    aliases = _flatten_dependency_maps(all_aliases_maps).pop(package_name, None)
+
+    if not aliases:
+        return dict()
+
+    common_items = aliases.pop(_COMMON_CONDITION, {}).items()
+
+    # If there are only common items in the dictionary, immediately return them
+    if not len(aliases.keys()) == 1:
+        return dict(common_items)
+
+    # Build a single select statement where each conditional has accounted for the
+    # common set of aliases.
+    crate_aliases = {"//conditions:default": common_items}
+    for condition, deps in aliases.items():
+        condition_triples = _CONDITIONS[condition]
+        if condition_triples in crate_aliases:
+            crate_aliases[condition_triples].update(deps)
+        else:
+            crate_aliases.update({_CONDITIONS[condition]: dict(deps.items() + common_items)})
+
+    return selects.with_or(crate_aliases)
+
+###############################################################################
+# WORKSPACE MEMBER DEPS AND ALIASES
+###############################################################################
+
+_NORMAL_DEPENDENCIES = {% set deps_type = "normal" %}{% include "partials/module/deps_map.j2" %}
+
+_NORMAL_ALIASES = {% set deps_type = "normal" %}{% include "partials/module/aliases_map.j2" %}
+
+_NORMAL_DEV_DEPENDENCIES = {% set deps_type = "normal-dev" %}{% include "partials/module/deps_map.j2" %}
+
+_NORMAL_DEV_ALIASES = {% set deps_type = "normal-dev" %}{% include "partials/module/aliases_map.j2" %}
+
+_PROC_MACRO_DEPENDENCIES = {% set deps_type = "proc-macro" %}{% include "partials/module/deps_map.j2" %}
+
+_PROC_MACRO_ALIASES = {% set deps_type = "proc-macro-dev" %}{% include "partials/module/aliases_map.j2" %}
+
+_PROC_MACRO_DEV_DEPENDENCIES = {% set deps_type = "proc-macro-dev" %}{% include "partials/module/deps_map.j2" %}
+
+_PROC_MACRO_DEV_ALIASES = {% set deps_type = "normal-dev" %}{% include "partials/module/aliases_map.j2" %}
+
+_BUILD_DEPENDENCIES = {% set deps_type = "build" %}{% include "partials/module/deps_map.j2" %}
+
+_BUILD_ALIASES = {% set deps_type = "build" %}{% include "partials/module/aliases_map.j2" %}
+
+_BUILD_PROC_MACRO_DEPENDENCIES = {% set deps_type = "build-proc-macro" %}{% include "partials/module/deps_map.j2" %}
+
+_BUILD_PROC_MACRO_ALIASES = {% set deps_type = "build-proc-macro" %}{% include "partials/module/aliases_map.j2" %}
+
+_CONDITIONS = {
+{%- for condition, triples in context.conditions %}
+    "{{ condition | addslashes }}": {{ triples | sort | json_encode | safe }},
+{%- endfor %}
+}
+{% set current_vendor_mode = vendor_mode | default(value="remote") %}{% if current_vendor_mode == "remote" %}
+###############################################################################
+
+def crate_repositories():
+    """A macro for defining repositories for all generated crates"""
+{%- if context.crates | length %}
+{%- for id, crate in context.crates %}
+{%- if not crate.repository %}{% continue %}{% endif %}
+{%- for repository_type, attrs in crate.repository %}
+{%- if repository_type in ["Http"] %}
+{% include "partials/module/repo_http.j2" %}
+{%- elif repository_type in ["Git"] %}
+{% include "partials/module/repo_git.j2" %}
+{%- else %}
+    {{ throw(message = "Unsupported checksum type: " ~ repository_type) }}
+{%- endif %}
+{%- endfor %}
+{%- endfor %}
+{%- else %}
+    pass
+{%- endif %}
+{%- endif %}
diff --git a/crate_universe/src/rendering/templates/partials/crate/aliases.j2 b/crate_universe/src/rendering/templates/partials/crate/aliases.j2
new file mode 100644
index 0000000..5c4b67e
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/crate/aliases.j2
@@ -0,0 +1,32 @@
+selects.with_or({
+    {%- for cfg, values in selectable.selects %}
+    {%- if cfg in context.conditions and context.conditions[cfg] | length %}
+        # {{ cfg }}
+        (
+            {%- for triple in context.conditions[cfg] %}
+            "{{ platform_label(triple = triple) }}",
+            {%- endfor %}
+        ): {
+            {%- for dep in values %}
+            {%- set dep_crate = context.crates | get(key=dep.id) %}
+            "{{ crate_label(name = dep_crate.name, version = dep_crate.version, target = dep.target) }}": "{{ dep.alias }}",
+            {%- endfor %}
+            {%- for dep in selectable.common %}
+            {%- set dep_crate = context.crates | get(key=dep.id) %}
+            "{{ crate_label(name = dep_crate.name, version = dep_crate.version, target = dep.target) }}": "{{ dep.alias }}",
+            {%- endfor %}
+        },
+    {%- else %}
+        # {
+        # No supported platform triples for cfg: '{{ cfg }}'
+        # Skipped dependencies: {{ values | json_encode | safe }}
+        # }
+    {%- endif %}
+    {%- endfor %}
+        "//conditions:default": {
+            {%- for dep in selectable.common %}
+            {%- set dep_crate = context.crates | get(key=dep.id) %}
+            "{{ crate_label(name = dep_crate.name, version = dep_crate.version, target = dep.target) }}": "{{ dep.alias }}",
+            {%- endfor %}
+        },
+    })
\ No newline at end of file
diff --git a/crate_universe/src/rendering/templates/partials/crate/binary.j2 b/crate_universe/src/rendering/templates/partials/crate/binary.j2
new file mode 100644
index 0000000..2cdc5d9
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/crate/binary.j2
@@ -0,0 +1,18 @@
+rust_binary(
+    name = "{{ target.crate_name }}__bin",
+    deps = [
+        {%- if crate.library_target_name %}
+        ":{{ crate.library_target_name }}",
+        {%- endif %}
+        {%- for dep in crate.common_attrs | get(key="extra_deps", default=[]) %}
+        "{{ dep }}",
+        {%- endfor %}
+    ] + {% set deps = crate.common_attrs | get(key="deps", default=Null) %}{% include "partials/crate/deps.j2" %},
+    proc_macro_deps = [
+        {%- for dep in crate.common_attrs | get(key="extra_proc_macro_deps", default=[]) %}
+        "{{ dep }}",
+        {%- endfor %}
+    ] + {% set deps = crate.common_attrs | get(key="proc_macro_deps", default=Null) %}{% include "partials/crate/deps.j2" %},
+    aliases = {% set selectable = common_aliases %}{% include "partials/crate/aliases.j2" -%},
+{% include "partials/crate/common_attrs.j2" %}
+)
diff --git a/crate_universe/src/rendering/templates/partials/crate/build_script.j2 b/crate_universe/src/rendering/templates/partials/crate/build_script.j2
new file mode 100644
index 0000000..45b97f7
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/crate/build_script.j2
@@ -0,0 +1,70 @@
+cargo_build_script(
+    # See comment associated with alias. Do not change this name
+    name = "{{ crate.name }}_build_script",
+    aliases = {% set selectable = build_aliases %}{% include "partials/crate/aliases.j2" -%},
+    build_script_env = {% set selectable = crate.build_script_attrs | get(key="build_script_env", default=Null) %}{% include "partials/starlark/selectable_dict.j2" -%},
+    compile_data = {% if crate.build_script_attrs | get(key="compile_data_glob") %}glob({{ crate.build_script_attrs.compile_data_glob | json_encode | safe }}) + {% endif %}{% set selectable = crate.build_script_attrs | get(key="compile_data", default=Null) %}{% include "partials/starlark/selectable_list.j2" %},
+    crate_name = "{{ sanitize_module_name(crate_name=target.crate_name) }}",
+    crate_root = "{{ target.crate_root }}",
+    crate_features = [
+        {%- if crate.common_attrs | get(key="crate_features", default=Null) %}
+        {%- for feature in crate.common_attrs.crate_features %}
+        "{{ feature }}",
+        {%- endfor %}
+        {%- endif %}
+    ],
+    data = {% if crate.build_script_attrs | get(key="data_glob") %}glob({{ crate.build_script_attrs.data_glob | json_encode | safe }}) + {% endif %}{% set selectable = crate.build_script_attrs | get(key="data", default=Null) %}{% include "partials/starlark/selectable_list.j2" %},
+    deps = [
+        {%- for dep in crate.build_script_attrs | get(key="extra_deps", default=[]) %}
+        "{{ dep }}",
+        {%- endfor %}
+    ] + {% set deps = crate.build_script_attrs | get(key="deps", default=Null) %}{% include "partials/crate/deps.j2" %},
+    edition = "{{ crate.common_attrs.edition }}",
+    {%- if crate.common_attrs.linker_script %}
+    linker_script = "{{ crate.common_attrs.linker_script }}",
+    {%- endif %}
+    {%- if crate.build_script_attrs | get(key="links", default=Null) %}
+    links = "{{ crate.build_script_attrs.links }}",
+    {%- endif %}
+    proc_macro_deps = [
+        {%- for dep in crate.build_script_attrs | get(key="extra_proc_macro_deps", default=[]) %}
+        "{{ dep }}",
+        {%- endfor %}
+    ] + {% set deps = crate.build_script_attrs | get(key="proc_macro_deps", default=Null) %}{% include "partials/crate/deps.j2" %},
+    rustc_env = {% set selectable = crate.build_script_attrs | get(key="rustc_env", default=Null) %}{% include "partials/starlark/selectable_dict.j2" -%},
+    rustc_env_files = {% set selectable = crate.build_script_attrs | get(key="rustc_env_files", default=Null) %}{% include "partials/starlark/selectable_list.j2" %},
+    rustc_flags = [
+        # In most cases, warnings in 3rd party crates are not interesting as
+        # they're out of the control of consumers. The flag here silences 
+        # warnings. For more details see: 
+        # https://doc.rust-lang.org/rustc/lints/levels.html
+        "--cap-lints=allow",
+    ] + {% set selectable = crate.build_script_attrs | get(key="rustc_flags", default=Null) %}{% include "partials/starlark/selectable_list.j2" %},
+    srcs = {% set glob = target.srcs %}{% include "partials/starlark/glob.j2" -%},
+    tools = {% set selectable = crate.build_script_attrs | get(key="tools", default=Null) %}{% include "partials/starlark/selectable_list.j2" %},
+    version = "{{ crate.common_attrs.version }}",
+    tags = [
+        {%- if crate.common_attrs | get(key="tags", default=Null) %}
+        {%- for tag in crate.common_attrs.tags %}
+        "{{ tag }}",
+        {%- endfor %}
+        {%- endif %}
+        "cargo-bazel",
+        "manual",
+        "noclippy",
+        "norustfmt",
+    ],
+    visibility = ["//visibility:private"],
+)
+alias(
+    # Because `cargo_build_script` does some invisible target name mutating to
+    # determine the package and crate name for a build script, the Bazel
+    # target namename of any build script cannot be the Cargo canonical name
+    # of `build_script_build` without losing out on having certain Cargo
+    # environment variables set.
+    name = "{{ target.crate_name }}",
+    actual = "{{ crate.name }}_build_script",
+    tags = [
+        "manual",
+    ],
+)
diff --git a/crate_universe/src/rendering/templates/partials/crate/common_attrs.j2 b/crate_universe/src/rendering/templates/partials/crate/common_attrs.j2
new file mode 100644
index 0000000..a381f44
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/crate/common_attrs.j2
@@ -0,0 +1,34 @@
+    compile_data = {% if crate.common_attrs | get(key="compile_data_glob") %}glob({{ crate.common_attrs.compile_data_glob | json_encode | safe }}) + {% endif %}{% set selectable = crate.common_attrs | get(key="compile_data", default=default_select_list) %}{% include "partials/starlark/selectable_list.j2" -%},
+    crate_root = "{{ target.crate_root }}",
+    crate_features = [
+        {%- for feature in crate.common_attrs | get(key="crate_features", default=[]) %}
+        "{{ feature }}",
+        {%- endfor %}
+    ],
+    data = {% if crate.common_attrs | get(key="data_glob") %}glob({{ crate.common_attrs.data_glob | json_encode | safe }}) + {% endif %}{% set selectable = crate.common_attrs | get(key="data", default=default_select_list) %}{% include "partials/starlark/selectable_list.j2" -%},
+    edition = "{{ crate.common_attrs.edition }}",
+    {%- if crate.common_attrs | get(key="linker_script", default=Null) %}
+    linker_script = "{{ crate.common_attrs.linker_script }}",
+    {%- endif %}
+    rustc_env = {% set selectable = crate.common_attrs | get(key="rustc_env", default=Null) %}{% include "partials/starlark/selectable_dict.j2" -%},
+    rustc_env_files = {% set selectable = crate.common_attrs | get(key="rustc_env_files", default=Null) %}{% include "partials/starlark/selectable_list.j2" -%},
+    rustc_flags = [
+        # In most cases, warnings in 3rd party crates are not interesting as
+        # they're out of the control of consumers. The flag here silences 
+        # warnings. For more details see: 
+        # https://doc.rust-lang.org/rustc/lints/levels.html
+        "--cap-lints=allow",
+    ] + {% set selectable = crate.common_attrs | get(key="rustc_flags", default=Null) %}{% include "partials/starlark/selectable_list.j2" -%},
+    srcs = {% set glob = target.srcs %}{% include "partials/starlark/glob.j2" -%},
+    version = "{{ crate.common_attrs.version }}",
+    tags = [
+        {%- if crate.common_attrs | get(key="tags", default=Null) %}
+        {%- for tag in crate.common_attrs.tags %}
+        "{{ tag }}",
+        {%- endfor %}
+        {%- endif %}
+        "cargo-bazel",
+        "manual",
+        "noclippy",
+        "norustfmt",
+    ],
diff --git a/crate_universe/src/rendering/templates/partials/crate/deps.j2 b/crate_universe/src/rendering/templates/partials/crate/deps.j2
new file mode 100644
index 0000000..0e0bf71
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/crate/deps.j2
@@ -0,0 +1,36 @@
+select_with_or({
+    {%- set selectable = deps | default(value=default_select_list) %}
+    {%- for cfg, values in selectable.selects %}
+        # {{ cfg }}
+    {%- if cfg in context.conditions and context.conditions[cfg] | length %}
+        (
+            {%- for triple in context.conditions[cfg] %}
+            "{{ platform_label(triple = triple) }}",
+            {%- endfor %}
+        ): [
+            # Target Deps
+            {%- for dep in values %}
+            {%- set dep_crate = context.crates | get(key=dep.id) %}
+            "{{ crate_label(name = dep_crate.name, version = dep_crate.version, target = dep.target) }}",
+            {%- endfor %}
+
+            # Common Deps
+            {%- for common_dep in selectable.common %}
+            {%- set common_dep_crate = context.crates | get(key=common_dep.id) %}
+            "{{ crate_label(name = common_dep_crate.name, version = common_dep_crate.version, target = common_dep.target) }}",
+            {%- endfor %}
+        ],
+    {%- else %}
+            #
+            # No supported platform triples for cfg: '{{ cfg }}'
+            # Skipped dependencies: {{ values | json_encode | safe }}
+            #
+    {%- endif %}
+    {%- endfor %}
+        "//conditions:default": [
+            {%- for common_dep in selectable.common %}
+            {%- set common_dep_crate = context.crates | get(key=common_dep.id) %}
+            "{{ crate_label(name = common_dep_crate.name, version = common_dep_crate.version, target = common_dep.target) }}",
+            {%- endfor %}
+        ],
+    })
\ No newline at end of file
diff --git a/crate_universe/src/rendering/templates/partials/crate/library.j2 b/crate_universe/src/rendering/templates/partials/crate/library.j2
new file mode 100644
index 0000000..f678bd9
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/crate/library.j2
@@ -0,0 +1,15 @@
+rust_library(
+    name = "{{ target.crate_name }}",
+    deps = [
+        {%- for dep in crate.common_attrs | get(key="extra_deps", default=[]) %}
+        "{{ dep }}",
+        {%- endfor %}
+    ] + {% set deps = crate.common_attrs | get(key="deps", default=Null) %}{% include "partials/crate/deps.j2" %},
+    proc_macro_deps = [
+        {%- for dep in crate.common_attrs | get(key="extra_proc_macro_deps", default=[]) %}
+        "{{ dep }}",
+        {%- endfor %}
+    ] + {% set deps = crate.common_attrs | get(key="proc_macro_deps", default=Null) %}{% include "partials/crate/deps.j2" %},
+    aliases = {% set selectable = common_aliases %}{% include "partials/crate/aliases.j2" -%},
+{% include "partials/crate/common_attrs.j2" %}
+)
diff --git a/crate_universe/src/rendering/templates/partials/crate/proc_macro.j2 b/crate_universe/src/rendering/templates/partials/crate/proc_macro.j2
new file mode 100644
index 0000000..c0b9d1d
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/crate/proc_macro.j2
@@ -0,0 +1,15 @@
+rust_proc_macro(
+    name = "{{ target.crate_name }}",
+    deps = [
+        {%- for dep in crate.common_attrs | get(key="extra_deps", default=[]) %}
+        "{{ dep }}",
+        {%- endfor %}
+    ] + {% set deps = crate.common_attrs | get(key="deps", default=Null) %}{% include "partials/crate/deps.j2" %},
+    proc_macro_deps = [
+        {%- for dep in crate.common_attrs | get(key="extra_proc_macro_deps", default=[]) %}
+        "{{ dep }}",
+        {%- endfor %}
+    ] + {% set deps = crate.common_attrs | get(key="proc_macro_deps", default=Null) %}{% include "partials/crate/deps.j2" %},
+    aliases = {% set selectable = common_aliases %}{% include "partials/crate/aliases.j2" -%},
+{% include "partials/crate/common_attrs.j2" %}
+)
diff --git a/crate_universe/src/rendering/templates/partials/header.j2 b/crate_universe/src/rendering/templates/partials/header.j2
new file mode 100644
index 0000000..6f88e85
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/header.j2
@@ -0,0 +1,6 @@
+###############################################################################
+# @generated
+# This file is auto-generated by the cargo-bazel tool.
+#
+# DO NOT MODIFY: Local changes may be replaced in future executions.
+###############################################################################
\ No newline at end of file
diff --git a/crate_universe/src/rendering/templates/partials/module/aliases_map.j2 b/crate_universe/src/rendering/templates/partials/module/aliases_map.j2
new file mode 100644
index 0000000..73d736e
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/module/aliases_map.j2
@@ -0,0 +1,53 @@
+{
+    {%- for id, path in context.workspace_members %}
+    {%- set workspace_member = context.crates | get(key=id) %}
+    "{{ path }}": {
+    {%- if deps_type in ["normal"] %}
+    {%- set_global deps_set = workspace_member.common_attrs | get(key="deps", default=default_select_list) %}
+    {%- elif deps_type in ["normal-dev"] %}
+    {%- set_global deps_set = workspace_member.common_attrs | get(key="deps_dev", default=default_select_list) %}
+    {%- elif deps_type in ["proc-macro"] %}
+    {%- set_global deps_set = workspace_member.common_attrs | get(key="proc_macro_deps", default=default_select_list) %}
+    {%- elif deps_type in ["proc-macro-dev"] %}
+    {%- set_global deps_set = workspace_member.common_attrs | get(key="proc_macro_deps_dev", default=default_select_list) %}
+    {%- elif deps_type in ["build"] %}
+        {%- if workspace_member | get(key="build_script_attrs", default=Null) %}
+        {%- set_global deps_set = workspace_member.build_script_attrs | get(key="deps", default=default_select_list) %}
+        {%- else %}
+        {%- set_global deps_set = default_select_list %}
+        {%- endif %}
+    {%- elif deps_type in ["build-proc-macro"] %}
+        {%- if workspace_member | get(key="build_script_attrs", default=Null) %}
+        {%- set_global deps_set = workspace_member.build_script_attrs | get(key="proc_macro_deps", default=default_select_list) %}
+        {%- else %}
+        {%- set_global deps_set = default_select_list %}
+        {%- endif %}
+    {%- else %}
+    {%- endif %}
+        {%- if deps_set.common | length %}
+        _COMMON_CONDITION: {
+            {%- for dep in deps_set.common %}
+            {%- if dep.id in context.workspace_members %}{% continue %}}{% endif %}{# Workspace member repositories are not defined, skip adding their labels here #}
+            {%- set crate = context.crates | get(key=dep.id) %}
+            {%- if dep | get(key="alias", default=Null) %}
+            "{{ crate_label(name = crate.name, version = crate.version, target = crate.name) }}": "{{ dep.alias }}",
+            {%- endif %}
+            {%- endfor %}
+        },
+        {%- endif %}
+        {%- if deps_set.selects | length %}
+        {%- for condition, deps in deps_set.selects %}
+        "{{ condition | addslashes }}": {
+            {%- for dep in deps %}
+            {%- if dep.id in context.workspace_members %}{% continue %}}{% endif %}{# Workspace member repositories are not defined, skip adding their labels here #}
+            {%- if dep | get(key="alias", default=Null) %}
+            {%- set crate = context.crates | get(key=dep.id) %}
+            "{{ crate_label(name = crate.name, version = crate.version, target = crate.name) }}": "{{ dep.alias }}",
+            {%- endif %}
+            {%- endfor %}
+        },
+        {%- endfor %}
+        {%- endif %}
+    },
+    {%- endfor %}
+}
diff --git a/crate_universe/src/rendering/templates/partials/module/deps_map.j2 b/crate_universe/src/rendering/templates/partials/module/deps_map.j2
new file mode 100644
index 0000000..c9f169d
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/module/deps_map.j2
@@ -0,0 +1,50 @@
+{
+    {%- for id, path in context.workspace_members %}
+    {%- set workspace_member = context.crates | get(key=id) %}
+    "{{ path }}": {
+    {%- if deps_type in ["normal"] %}
+    {%- set_global deps_set = workspace_member.common_attrs | get(key="deps", default=default_select_list) %}
+    {%- elif deps_type in ["normal-dev"] %}
+    {%- set_global deps_set = workspace_member.common_attrs | get(key="deps_dev", default=default_select_list) %}
+    {%- elif deps_type in ["proc-macro"] %}
+    {%- set_global deps_set = workspace_member.common_attrs | get(key="proc_macro_deps", default=default_select_list) %}
+    {%- elif deps_type in ["proc-macro-dev"] %}
+    {%- set_global deps_set = workspace_member.common_attrs | get(key="proc_macro_deps_dev", default=default_select_list) %}
+    {%- elif deps_type in ["build"] %}
+        {%- if workspace_member | get(key="build_script_attrs", default=Null) %}
+        {%- set_global deps_set = workspace_member.build_script_attrs | get(key="deps", default=default_select_list) %}
+        {%- else %}
+        {%- set_global deps_set = default_select_list %}
+        {%- endif %}
+    {%- elif deps_type in ["build-proc-macro"] %}
+        {%- if workspace_member | get(key="build_script_attrs", default=Null) %}
+        {%- set_global deps_set = workspace_member.build_script_attrs | get(key="proc_macro_deps", default=default_select_list) %}
+        {%- else %}
+        {%- set_global deps_set = default_select_list %}
+        {%- endif %}
+    {%- else %}
+    {{ throw(message= "Unexpected dependency type '" ~ deps_type ~ "' for '" ~ id ~ "'") }}
+    {%- endif %}
+        {%- if deps_set.common | length %}
+        _COMMON_CONDITION: {
+            {%- for dep in deps_set.common %}
+            {%- if dep.id in context.workspace_members %}{% continue %}}{% endif %}{# Workspace member repositories are not defined, skip adding their labels here #}
+            {%- set crate = context.crates | get(key=dep.id) %}
+            "{{ dep | get(key="alias", default=crate.name) }}": "{{ crate_label(name = crate.name, version = crate.version, target = dep.target) }}",
+            {%- endfor %}
+        },
+        {%- endif %}
+        {%- if deps_set.selects | length %}
+        {%- for condition, deps in deps_set.selects %}
+        "{{ condition | addslashes }}": {
+            {%- for dep in deps %}
+            {%- if dep.id in context.workspace_members %}{% continue %}}{% endif %}{# Workspace member repositories are not defined, skip adding their labels here #}
+            {%- set crate = context.crates | get(key=dep.id) %}
+            "{{ dep | get(key="alias", default=crate.name) }}": "{{ crate_label(name = crate.name, version = crate.version, target = dep.target) }}",
+            {%- endfor %}
+        },
+        {%- endfor %}
+        {%- endif %}
+    },
+    {%- endfor %}
+}
diff --git a/crate_universe/src/rendering/templates/partials/module/repo_git.j2 b/crate_universe/src/rendering/templates/partials/module/repo_git.j2
new file mode 100644
index 0000000..3bc2392
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/module/repo_git.j2
@@ -0,0 +1,41 @@
+    maybe(
+        new_git_repository,
+        name = "{{ crate_repository(name = crate.name, version = crate.version) }}",
+    {%- for type, commitish in attrs.commitish %}
+    {%- if type in ["Rev"] %}
+        commit = "{{ commitish }}",
+    {%- elif type in ["Tag"] %}
+        tag = "{{ commitish }}",
+    {%- elif type in ["Branch"] %}
+        branch = "{{ commitish }}",
+    {%- else %}
+        {{ throw(message= "Unexpected git commitish '" ~ type ~ "' for '" ~ crate.name ~ "'") }}
+    {%- endif %}
+    {%- endfor %}
+        init_submodules = True,
+    {%- if attrs | get(key="patch_args", default=Null) %}
+        patch_args = [
+    {%- for arg in attrs.patch_args %}
+            "{{ arg }}",
+    {%- endfor %}
+        ],
+    {%- endif %}
+    {%- if attrs | get(key="patch_tool", default=Null) %}
+        patch_tool = "{{ attrs.patch_tool }}",
+    {%- endif %}
+    {%- if attrs | get(key="patches", default=Null) %}
+        patches = [
+    {%- for patch in attrs.patches %}
+            "{{ patch }}",
+    {%- endfor %}
+        ],
+    {%- endif %}
+    {%- if attrs | get(key="shallow_since", default=Null) %}
+        shallow_since = "{{ attrs.shallow_since }}",
+    {%- endif %}
+        remote = "{{ attrs.remote }}",
+        build_file = Label("{{ crate_build_file(name = crate.name, version = crate.version)}}"),
+    {%- if attrs.strip_prefix %}
+        strip_prefix = "{{ attrs.strip_prefix }}",
+    {%- endif %}
+    )
diff --git a/crate_universe/src/rendering/templates/partials/module/repo_http.j2 b/crate_universe/src/rendering/templates/partials/module/repo_http.j2
new file mode 100644
index 0000000..8e3f7dc
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/module/repo_http.j2
@@ -0,0 +1,28 @@
+    maybe(
+        http_archive,
+        name = "{{ crate_repository(name = crate.name, version = crate.version) }}",
+    {%- if attrs | get(key="patch_args", default=Null) %}
+        patch_args = [
+    {%- for arg in attrs.patch_args %}
+            "{{ arg }}",
+    {%- endfor %}
+        ],
+    {%- endif %}
+    {%- if attrs | get(key="patch_tool", default=Null) %}
+        patch_tool = "{{ attrs.patch_tool }}",
+    {%- endif %}
+    {%- if attrs | get(key="patches", default=Null) %}
+        patches = [
+    {%- for patch in attrs.patches %}
+            "{{ patch }}",
+    {%- endfor %}
+        ],
+    {%- endif %}
+    {%- if attrs | get(key="sha256", default=Null) %}
+        sha256 = "{{ attrs.sha256 }}",
+    {%- endif %}
+        type = "tar.gz",
+        urls = ["{{ attrs.url }}"],
+        strip_prefix = "{{ crate.name }}-{{ crate.version }}",
+        build_file = Label("{{ crate_build_file(name = crate.name, version = crate.version)}}"),
+    )
diff --git a/crate_universe/src/rendering/templates/partials/starlark/glob.j2 b/crate_universe/src/rendering/templates/partials/starlark/glob.j2
new file mode 100644
index 0000000..67f70af
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/starlark/glob.j2
@@ -0,0 +1,12 @@
+glob(
+        include = [
+            {%- for pattern in glob.include %}
+            "{{ pattern }}",
+            {%- endfor %}
+        ],
+        exclude = [
+            {%- for pattern in glob.exclude %}
+            "{{ pattern }}",
+            {%- endfor %}
+        ],
+    )
\ No newline at end of file
diff --git a/crate_universe/src/rendering/templates/partials/starlark/selectable_dict.j2 b/crate_universe/src/rendering/templates/partials/starlark/selectable_dict.j2
new file mode 100644
index 0000000..8012cc7
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/starlark/selectable_dict.j2
@@ -0,0 +1,36 @@
+{%- set selectable = selectable | default(value=default_select_dict) %}
+{%- if selectable.selects | length -%}
+    selects.with_or({
+    {%- for cfg, map in selectable.selects %}
+    {%- if cfg in context.conditions and context.conditions[cfg] | length %}
+        # {{ cfg }}
+        (
+            {%- for triple in context.conditions[cfg] %}
+            "{{ platform_label(triple = triple) }}",
+            {%- endfor %}
+        ): {
+            {%- if selectable.common | length %}
+            {%- for key, val in selectable.common %}
+            "{{ key }}": "{{ val }}",
+            {%- endfor %}
+            {%- endif %}
+            {%- for key, val in map %}
+            "{{ key }}": "{{ val }}",
+            {%- endfor %}
+        },
+    {%- else %}
+        # No supported platform triples for cfg: '{{ cfg }}'
+        # Skipped dependencies: {{ map | json_encode| safe }}
+    {%- endif %}
+    {%- endfor %}
+        "//conditions:default": {},
+    })
+{%- else -%}
+    {
+        {%- if selectable.common | length %}
+        {%- for key, val in selectable.common %}
+        "{{ key }}": "{{ val }}",
+        {%- endfor %}
+        {%- endif %}
+    }
+{%- endif %}
\ No newline at end of file
diff --git a/crate_universe/src/rendering/templates/partials/starlark/selectable_list.j2 b/crate_universe/src/rendering/templates/partials/starlark/selectable_list.j2
new file mode 100644
index 0000000..2641713
--- /dev/null
+++ b/crate_universe/src/rendering/templates/partials/starlark/selectable_list.j2
@@ -0,0 +1,31 @@
+select_with_or({
+    {%- set selectable = selectable | default(value=default_select_list) %}
+    {%- for cfg, values in selectable.selects %}
+        # {{ cfg }}
+    {%- if cfg in context.conditions and context.conditions[cfg] | length %}
+        (
+            {%- for triple in context.conditions[cfg] %}
+            "{{ platform_label(triple = triple) }}",
+            {%- endfor %}
+        ): [
+            # Target Deps
+            {%- for val in values %}
+            "{{ val }}",
+            {%- endfor %}
+
+            # Common Deps
+            {%- for val in selectable.common %}
+            "{{ val }}",
+            {%- endfor %}
+        ],
+    {%- else %}
+            # No supported platform triples for cfg: '{{ cfg }}'
+            # Skipped dependencies: {{ values | json_encode | safe }}
+    {%- endif %}
+    {%- endfor %}
+        "//conditions:default": [
+            {%- for val in selectable.common %}
+            "{{ val }}",
+            {%- endfor %}
+        ],
+    })
\ No newline at end of file
diff --git a/crate_universe/src/rendering/templates/vendor_module.j2 b/crate_universe/src/rendering/templates/vendor_module.j2
new file mode 100644
index 0000000..74b031e
--- /dev/null
+++ b/crate_universe/src/rendering/templates/vendor_module.j2
@@ -0,0 +1,25 @@
+###############################################################################
+# @generated
+# This file is auto-generated by the cargo-bazel tool.
+#
+# DO NOT MODIFY: Local changes may be replaced in future executions.
+###############################################################################
+"""Rules for defining repositories for remote `crates_vendor` repositories"""
+
+load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
+
+# buildifier: disable=bzl-visibility
+load("@rules_rust//crate_universe/private:crates_vendor.bzl", "crates_vendor_remote_repository")
+
+# buildifier: disable=bzl-visibility
+load("{{ crates_module_label(file="defs.bzl") }}", _crate_repositories = "crate_repositories")
+
+def crate_repositories():
+    maybe(
+        crates_vendor_remote_repository,
+        name = "{{ repository_name }}",
+        build_file = Label("{{ crates_module_label(file="BUILD.bazel") }}"),
+        defs_module = Label("{{ crates_module_label(file="defs.bzl") }}"),
+    )
+
+    _crate_repositories()