use std::ffi::OsStr;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct BuildOutputs {
pub verbose_log: String,
pub timing_html: String,
pub cargo_metadata: Option<String>,
}
pub const VERBOSE_LOG_NAME: &str = "verbose.log";
pub const TIMING_REPORT_NAME: &str = "cargo-timing.html";
pub const METADATA_NAME: &str = "cargo-metadata.json";
pub fn from_directory(directory: &Path) -> io::Result<BuildOutputs> {
let metadata_path = directory.join(METADATA_NAME);
Ok(BuildOutputs {
verbose_log: read_text(&directory.join(VERBOSE_LOG_NAME))?,
timing_html: read_text(&directory.join(TIMING_REPORT_NAME))?,
cargo_metadata: read_text(&metadata_path).ok(),
})
}
pub fn from_paths(
verbose_log: &Path,
timing_report: &Path,
cargo_metadata: Option<&Path>,
) -> io::Result<BuildOutputs> {
Ok(BuildOutputs {
verbose_log: read_text(verbose_log)?,
timing_html: read_text(timing_report)?,
cargo_metadata: match cargo_metadata {
Some(path) => Some(read_text(path)?),
None => None,
},
})
}
pub fn latest_timing_report(target_directory: &Path) -> io::Result<PathBuf> {
let timings = target_directory.join("cargo-timings");
let current = timings.join(TIMING_REPORT_NAME);
if current.is_file() {
return Ok(current);
}
let mut dated: Vec<PathBuf> = fs::read_dir(&timings)
.map(|entries| {
entries
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| {
path.extension() == Some(OsStr::new("html"))
&& path
.file_name()
.and_then(OsStr::to_str)
.is_some_and(|name| name.starts_with("cargo-timing"))
})
.collect()
})
.unwrap_or_default();
dated.sort();
dated.pop().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!(
"no timing report under {}; produce one with \
`cargo build --timings -v --offline 2>build.log`",
timings.display()
),
)
})
}
pub fn run_cargo_metadata(manifest_path: &Path) -> io::Result<String> {
let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
let output = Command::new(cargo)
.arg("metadata")
.arg("--format-version")
.arg("1")
.arg("--offline")
.arg("--no-deps")
.arg("--manifest-path")
.arg(manifest_path)
.output()?;
if !output.status.success() {
return Err(io::Error::other(format!(
"`cargo metadata` failed for {}: {}",
manifest_path.display(),
String::from_utf8_lossy(&output.stderr).trim()
)));
}
String::from_utf8(output.stdout)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))
}
pub fn read_text(path: &Path) -> io::Result<String> {
let bytes = fs::read(path)?;
let wide = matches!(bytes.get(..2), Some([0xFF, 0xFE] | [0xFE, 0xFF]));
if wide {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"{} begins with a UTF-16 byte-order mark, but Cargo writes UTF-8; \
a redirection under PowerShell writes UTF-16. Capture it with \
`cargo build --timings -v --offline 2>&1 | Out-File -Encoding utf8 build.log`, \
or from a shell that redirects as UTF-8",
path.display()
),
));
}
String::from_utf8(bytes).map_err(|error| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"{} is not UTF-8 text, which is what Cargo writes ({}); \
capture it again with `cargo build --timings -v --offline 2>build.log`, \
and check that nothing has rewritten or truncated the file since",
path.display(),
error.utf8_error()
),
)
})
}