cargo_bazel/cli/
splice.rs

1//! The cli entrypoint for the `splice` subcommand
2
3use std::path::PathBuf;
4
5use anyhow::Context;
6use camino::Utf8PathBuf;
7use clap::Parser;
8
9use crate::cli::Result;
10use crate::config::Config;
11use crate::metadata::{
12    write_metadata, Cargo, CargoUpdateRequest, Generator, MetadataGenerator, TreeResolver,
13};
14use crate::splicing::{generate_lockfile, Splicer, SplicingManifest, WorkspaceMetadata};
15
16/// Command line options for the `splice` subcommand
17#[derive(Parser, Debug)]
18#[clap(about = "Command line options for the `splice` subcommand", version)]
19pub struct SpliceOptions {
20    /// A generated manifest of splicing inputs
21    #[clap(long)]
22    pub splicing_manifest: PathBuf,
23
24    /// The path to a [Cargo.lock](https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html) file.
25    #[clap(long)]
26    pub cargo_lockfile: Option<PathBuf>,
27
28    /// The desired update/repin behavior
29    #[clap(long, env = "CARGO_BAZEL_REPIN", num_args=0..=1, default_missing_value = "true")]
30    pub repin: Option<CargoUpdateRequest>,
31
32    /// The directory in which to build the workspace. If this argument is not
33    /// passed, a temporary directory will be generated.
34    #[clap(long)]
35    pub workspace_dir: Option<Utf8PathBuf>,
36
37    /// The location where the results of splicing are written.
38    #[clap(long)]
39    pub output_dir: PathBuf,
40
41    /// If true, outputs will be printed instead of written to disk.
42    #[clap(long)]
43    pub dry_run: bool,
44
45    /// The path to a Cargo configuration file.
46    #[clap(long)]
47    pub cargo_config: Option<PathBuf>,
48
49    /// The path to the config file (containing [crate::config::Config].)
50    #[clap(long)]
51    pub config: PathBuf,
52
53    /// The path to a Cargo binary to use for gathering metadata
54    #[clap(long, env = "CARGO")]
55    pub cargo: PathBuf,
56
57    /// The path to a rustc binary for use with Cargo
58    #[clap(long, env = "RUSTC")]
59    pub rustc: PathBuf,
60}
61
62/// Combine a set of disjoint manifests into a single workspace.
63pub fn splice(opt: SpliceOptions) -> Result<()> {
64    // Load the all config files required for splicing a workspace
65    let splicing_manifest = SplicingManifest::try_from_path(&opt.splicing_manifest)
66        .context("Failed to parse splicing manifest")?;
67
68    // Determine the splicing workspace
69    let temp_dir;
70    let splicing_dir = match &opt.workspace_dir {
71        Some(dir) => dir.clone(),
72        None => {
73            temp_dir = tempfile::tempdir().context("Failed to generate temporary directory")?;
74            Utf8PathBuf::from_path_buf(temp_dir.as_ref().to_path_buf())
75                .unwrap_or_else(|path| panic!("Temporary directory wasn't valid UTF-8: {:?}", path))
76        }
77    };
78
79    // Generate a splicer for creating a Cargo workspace manifest
80    let splicer = Splicer::new(splicing_dir, splicing_manifest)?;
81
82    let cargo = Cargo::new(opt.cargo, opt.rustc.clone());
83
84    // Splice together the manifest
85    let manifest_path = splicer
86        .splice_workspace()
87        .context("Failed to splice workspace")?;
88
89    // Generate a lockfile
90    let cargo_lockfile = generate_lockfile(
91        &manifest_path,
92        &opt.cargo_lockfile,
93        cargo.clone(),
94        &opt.repin,
95    )
96    .context("Failed to generate lockfile")?;
97
98    let config = Config::try_from_path(&opt.config).context("Failed to parse config")?;
99
100    let resolver_data = TreeResolver::new(cargo.clone())
101        .generate(
102            manifest_path.as_path_buf(),
103            &config.supported_platform_triples,
104        )
105        .context("Failed to generate features")?;
106    // Write the registry url info to the manifest now that a lockfile has been generated
107    WorkspaceMetadata::write_registry_urls_and_feature_map(
108        &cargo,
109        &cargo_lockfile,
110        resolver_data,
111        manifest_path.as_path_buf(),
112        manifest_path.as_path_buf(),
113    )
114    .context("Failed to write registry URLs and feature map")?;
115
116    let output_dir = opt.output_dir.clone();
117
118    // Write metadata to the workspace for future reuse
119    let (cargo_metadata, _) = Generator::new()
120        .with_cargo(cargo)
121        .with_rustc(opt.rustc)
122        .generate(manifest_path.as_path_buf())
123        .context("Failed to generate cargo metadata")?;
124
125    let cargo_lockfile_path = manifest_path
126        .as_path_buf()
127        .parent()
128        .with_context(|| {
129            format!(
130                "The path {} is expected to have a parent directory",
131                manifest_path.as_path_buf()
132            )
133        })?
134        .join("Cargo.lock");
135
136    // Generate the consumable outputs of the splicing process
137    std::fs::create_dir_all(&output_dir)
138        .with_context(|| format!("Failed to create directories for {}", &output_dir.display()))?;
139
140    write_metadata(&opt.output_dir.join("metadata.json"), &cargo_metadata)
141        .context("Failed to write metadata")?;
142
143    std::fs::copy(cargo_lockfile_path, output_dir.join("Cargo.lock"))
144        .context("Failed to copy lockfile")?;
145
146    Ok(())
147}