use std::borrow::Cow;
use std::path::Path;
use std::path::PathBuf;
use cargo::CargoResult;
use cargo::core::Workspace;
use cargo::core::compiler::CompileKind;
use cargo::core::compiler::CompileTarget;
use cargo::core::profiles::Profiles;
use cargo_util::paths;
use crate::config::Config;
use super::Layout;
use super::LayoutLockable;
#[allow(dead_code)]
pub struct CargoLayout {
root: PathBuf,
dest: PathBuf,
deps: PathBuf,
build: PathBuf,
artifact: PathBuf,
incremental: PathBuf,
fingerprint: PathBuf,
examples: PathBuf,
doc: PathBuf,
tmp: PathBuf,
}
impl AsRef<CargoLayout> for &'_ CargoLayout {
fn as_ref(&self) -> &CargoLayout { self }
}
impl CargoLayout {
pub fn new(ws: &Workspace<'_>, target: Option<CompileTarget>, dest: &str) -> CargoResult<CargoLayout> {
let mut root = ws.target_dir();
if let Some(target) = target {
root.push(target.short_name());
}
let dest = root.join(dest);
let root = root.into_path_unlocked();
let dest = dest.into_path_unlocked();
let deps = dest.join("deps");
let artifact = deps.join("artifact");
Ok(CargoLayout { deps,
build: dest.join("build"),
artifact,
incremental: dest.join("incremental"),
fingerprint: dest.join(".fingerprint"),
examples: dest.join("examples"),
doc: root.join("doc"),
tmp: root.join("tmp"),
root,
dest })
}
}
impl Layout for CargoLayout {
fn root(&self) -> &Path { &self.root }
fn dest(&self) -> Cow<Path> { self.dest.as_path().into() }
fn create_dest_dir(&mut self) -> anyhow::Result<()> {
if !self.root.try_exists()? {
paths::create_dir_all_excluded_from_backups_atomic(&self.root)?;
}
if !self.dest.try_exists()? {
paths::create_dir_all(&self.dest)?;
}
Ok(())
}
fn prepare(&mut self) -> anyhow::Result<()> {
paths::create_dir_all(&self.deps)?;
paths::create_dir_all(&self.incremental)?;
paths::create_dir_all(&self.fingerprint)?;
paths::create_dir_all(&self.examples)?;
paths::create_dir_all(&self.build)?;
Ok(())
}
}
impl LayoutLockable for CargoLayout {
fn lockfilename(&self) -> Cow<'static, str> { ".cargo-lock".into() }
}
impl<'cfg> Config<'cfg> {
pub fn layout(&self, target: Option<CompileTarget>) -> anyhow::Result<CargoLayout> {
let profiles = Profiles::new(
&self.workspace,
self.compile_options.build_config.requested_profile,
)?;
let layout = CargoLayout::new(&self.workspace, target, profiles.get_dir_name().as_str())?;
if let Some(export_dir) = self.compile_options.build_config.export_dir.as_deref() {
debug_assert_eq!(layout.dest(), export_dir)
}
Ok(layout)
}
pub fn layout_for(&self, kind: CompileKind) -> anyhow::Result<CargoLayout> {
let target = match kind {
CompileKind::Host => None,
CompileKind::Target(target) => Some(target),
};
self.layout(target)
}
}