use critpath_core::{EdgeKind, UnitKind};
use crate::error::ParseError;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Role {
Compile,
BuildScriptRun,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub struct PackageRef {
pub name: String,
pub version: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExternRef {
pub name: String,
pub extension: String,
pub edge: EdgeKind,
pub producer: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Invocation {
pub position: usize,
pub role: Role,
pub crate_name: String,
pub crate_types: Vec<String>,
pub emits: Vec<String>,
pub pipelined: bool,
pub extra_filename: Option<String>,
pub metadata_hash: Option<String>,
pub externs: Vec<ExternRef>,
pub source_path: String,
pub features: Vec<String>,
pub registry_package: Option<PackageRef>,
pub directory_package: Option<String>,
pub run_package: Option<String>,
pub run_artifact: Option<String>,
pub kind: UnitKind,
pub requires_full_closure: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct VerboseLog {
pub invocations: Vec<Invocation>,
pub unrecognised: Vec<String>,
}
pub fn parse(text: &str) -> Result<VerboseLog, ParseError> {
crate::error::reject_wide_text(text, "build log")?;
let mut invocations = Vec::new();
let mut unrecognised = Vec::new();
for command in commands(text) {
let argv = split_command(&command).ok_or_else(|| ParseError::UnbalancedQuoting {
line: truncate(&command),
})?;
let position = invocations.len();
match classify(&argv, position) {
Some(invocation) => invocations.push(invocation),
None => unrecognised.push(command),
}
}
if invocations.is_empty() {
return Err(ParseError::NoInvocations);
}
Ok(VerboseLog {
invocations,
unrecognised,
})
}
fn commands(text: &str) -> Vec<String> {
const MARKER: &str = "Running `";
let mut out = Vec::new();
let mut pending: Option<String> = None;
for raw in text.lines() {
let line = raw.strip_suffix('\r').unwrap_or(raw);
match pending.take() {
Some(mut open) => {
open.push('\n');
match line.strip_suffix('`') {
Some(rest) => {
open.push_str(rest);
out.push(open);
}
None => {
open.push_str(line);
pending = Some(open);
}
}
}
None => {
let trimmed = line.trim_start();
let Some(rest) = trimmed.strip_prefix(MARKER) else {
continue;
};
match rest.strip_suffix('`') {
Some(command) => out.push(command.to_owned()),
None => pending = Some(rest.to_owned()),
}
}
}
}
if let Some(open) = pending {
out.push(open);
}
out
}
fn split_command(command: &str) -> Option<Vec<String>> {
let mut args = Vec::new();
let mut current = String::new();
let mut started = false;
let mut chars = command.chars();
while let Some(c) = chars.next() {
match c {
' ' | '\t' | '\n' => {
if started {
args.push(core::mem::take(&mut current));
started = false;
}
}
'\'' => {
started = true;
loop {
match chars.next() {
Some('\'') => break,
Some(inner) => current.push(inner),
None => return None,
}
}
}
'"' => {
started = true;
loop {
match chars.next() {
Some('"') => break,
Some('\\') => match chars.next() {
Some(escaped @ ('"' | '\\')) => current.push(escaped),
Some(literal) => {
current.push('\\');
current.push(literal);
}
None => return None,
},
Some(inner) => current.push(inner),
None => return None,
}
}
}
'\\' => {
started = true;
match chars.next() {
Some(escaped @ ('\'' | '!')) => current.push(escaped),
Some(literal) => {
current.push('\\');
current.push(literal);
}
None => return None,
}
}
other => {
started = true;
current.push(other);
}
}
}
if started {
args.push(current);
}
Some(args)
}
fn classify(argv: &[String], position: usize) -> Option<Invocation> {
if let Some(first) = argv.first() {
if file_stem(first) == "build-script-build" {
let (package, artifact) = split_build_directory(parent_of(first));
return Some(Invocation {
position,
role: Role::BuildScriptRun,
crate_name: String::new(),
crate_types: Vec::new(),
emits: Vec::new(),
pipelined: false,
extra_filename: None,
metadata_hash: None,
externs: Vec::new(),
source_path: String::new(),
features: Vec::new(),
registry_package: None,
directory_package: None,
run_package: package,
run_artifact: artifact,
kind: UnitKind::BuildScriptRun,
requires_full_closure: false,
});
}
}
let compiler = argv.iter().position(|a| file_stem(a) == "rustc")?;
let args = argv.get(compiler.checked_add(1)?..)?;
let crate_name = value_of(args, "--crate-name")?.to_owned();
let crate_types: Vec<String> = values_of(args, "--crate-type");
let emits: Vec<String> = value_of(args, "--emit")
.unwrap_or_default()
.split(',')
.filter(|s| !s.is_empty())
.map(str::to_owned)
.collect();
let source_path = args
.iter()
.find(|a| a.ends_with(".rs"))
.cloned()
.unwrap_or_default();
let codegen: Vec<&str> = values_of_borrowed(args, "-C");
let extra_filename = codegen
.iter()
.find_map(|v| v.strip_prefix("extra-filename="))
.map(str::to_owned);
let metadata_hash = codegen
.iter()
.find_map(|v| v.strip_prefix("metadata="))
.map(str::to_owned);
let mut features: Vec<String> = values_of_borrowed(args, "--cfg")
.iter()
.filter_map(|v| {
v.strip_prefix("feature=\"")
.and_then(|v| v.strip_suffix('"'))
})
.map(str::to_owned)
.collect();
features.sort();
features.dedup();
let externs = values_of_borrowed(args, "--extern")
.iter()
.filter_map(|spec| extern_ref(spec))
.collect();
let out_dir = value_of(args, "--out-dir").unwrap_or_default();
let (build_package, _) = split_build_directory(out_dir);
let is_build_script = build_package.is_some();
let has_test_harness = args.iter().any(|a| a == "--test" || a == "--bench");
let (kind, requires_full_closure) = if is_build_script {
(UnitKind::BuildScriptCompile, true)
} else if has_test_harness {
(UnitKind::Test, true)
} else if crate_types.iter().any(|t| t == "proc-macro") {
(UnitKind::ProcMacro, true)
} else if crate_types.is_empty() || crate_types.iter().any(|t| t == "bin") {
(UnitKind::Bin, true)
} else if crate_types.iter().all(|t| t == "lib" || t == "rlib") {
(UnitKind::Lib, false)
} else {
(UnitKind::Other, true)
};
Some(Invocation {
position,
role: Role::Compile,
pipelined: emits.iter().any(|e| e == "metadata"),
registry_package: registry_package(&source_path),
directory_package: directory_package(&source_path),
run_package: build_package,
run_artifact: None,
crate_name,
crate_types,
emits,
extra_filename,
metadata_hash,
externs,
source_path,
features,
kind,
requires_full_closure,
})
}
fn extern_ref(spec: &str) -> Option<ExternRef> {
let (name, path) = spec.split_once('=')?;
let file = file_name(path);
let (stem, extension) = match file.rsplit_once('.') {
Some((stem, extension)) => (stem, extension),
None => (file, ""),
};
Some(ExternRef {
name: name.to_owned(),
extension: extension.to_owned(),
edge: if extension == "rmeta" {
EdgeKind::Metadata
} else {
EdgeKind::Full
},
producer: trailing_hash(stem).map(str::to_owned),
})
}
fn split_build_directory(dir: &str) -> (Option<String>, Option<String>) {
if file_name(parent_of(dir)) != "build" {
return (None, None);
}
let leaf = file_name(dir);
match trailing_hash(leaf) {
Some(hash) => {
let name = leaf.get(..leaf.len().saturating_sub(hash.len()));
(name.map(str::to_owned), Some(hash.to_owned()))
}
None => (None, None),
}
}
fn trailing_hash(stem: &str) -> Option<&str> {
let dash = stem.rfind('-')?;
let hash = stem.get(dash..)?;
let digits = hash.get(1..)?;
if digits.len() >= 8 && digits.chars().all(|c| c.is_ascii_hexdigit()) {
Some(hash)
} else {
None
}
}
fn registry_package(source: &str) -> Option<PackageRef> {
for component in components(source) {
let Some(dash) = component.rfind('-') else {
continue;
};
let (name, version) = (
component.get(..dash)?,
component.get(dash.saturating_add(1)..)?,
);
if name.is_empty() || !looks_like_version(version) {
continue;
}
return Some(PackageRef {
name: name.to_owned(),
version: version.to_owned(),
});
}
None
}
fn looks_like_version(text: &str) -> bool {
let mut parts = text.split('.');
let (Some(major), Some(minor), Some(patch)) = (parts.next(), parts.next(), parts.next()) else {
return false;
};
let numeric = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit());
let patch_number = patch.split(['-', '+']).next().unwrap_or_default();
numeric(major) && numeric(minor) && numeric(patch_number)
}
fn directory_package(source: &str) -> Option<String> {
let mut parts: Vec<&str> = components(parent_of(source)).collect();
while matches!(
parts.last().copied(),
Some("src" | "bin" | "examples" | "tests" | "benches")
) {
parts.pop();
}
parts.last().map(|s| (*s).to_owned())
}
fn components(path: &str) -> impl DoubleEndedIterator<Item = &str> {
const SEPARATORS: &[char] = &['/', '\\'];
path.split(SEPARATORS).filter(|s| !s.is_empty())
}
fn file_name(path: &str) -> &str {
components(path).next_back().unwrap_or("")
}
fn file_stem(path: &str) -> &str {
let name = file_name(path);
name.strip_suffix(".exe").unwrap_or(name)
}
fn parent_of(path: &str) -> &str {
match path.rfind(['/', '\\']) {
Some(at) => path.get(..at).unwrap_or(""),
None => "",
}
}
fn value_of<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
values_of_borrowed(args, name).first().copied()
}
fn values_of(args: &[String], name: &str) -> Vec<String> {
values_of_borrowed(args, name)
.into_iter()
.map(str::to_owned)
.collect()
}
fn values_of_borrowed<'a>(args: &'a [String], name: &str) -> Vec<&'a str> {
let mut out = Vec::new();
let mut expecting = false;
for arg in args {
if expecting {
out.push(arg.as_str());
expecting = false;
continue;
}
if arg == name {
expecting = true;
} else if let Some(rest) = arg.strip_prefix(name) {
if let Some(value) = rest.strip_prefix('=') {
out.push(value);
} else if name.len() == 2 && !rest.is_empty() {
out.push(rest);
}
}
}
out
}
fn truncate(line: &str) -> String {
const LIMIT: usize = 120;
match line.char_indices().nth(LIMIT) {
Some((at, _)) => match line.get(..at) {
Some(head) => format!("{head}…"),
None => line.to_owned(),
},
None => line.to_owned(),
}
}