use super::{CaptureInventory, capture_file, capture_software_tree};
use crate::{artifact::ArtifactRole, config::ResolvedProgramTask, storage::Store};
use serde_json::{Value, json};
use std::{
io,
path::{Path, PathBuf},
process::Command,
};
pub(crate) fn libraries(
store: &Store,
binary: &Path,
root: &Path,
inventory: &mut CaptureInventory,
) -> io::Result<()> {
let result = Command::new("ldd").arg(binary).output()?;
if !result.status.success() {
return Ok(());
} for word in String::from_utf8_lossy(&result.stdout).split_whitespace() {
if word.starts_with('/') {
let path = Path::new(word).canonicalize()?;
let key = format!(
"reproduction/libraries/{}",
Path::new(word).file_name().unwrap().to_string_lossy()
);
if inventory.contains_key(&key) {
let digest = crate::artifact::digest_reader(std::fs::File::open(&path)?)?.0;
if inventory[&key].sha256 != digest {
return Err(io::Error::other(
"two captured environments require conflicting shared libraries",
));
}
continue;
}
capture_file(
store,
&path,
&key,
Some(&root.join(&key)),
inventory,
ArtifactRole::Reproduction,
)?;
}
}
Ok(())
}
pub(crate) fn python(
store: &Store,
program: &ResolvedProgramTask,
root: &Path,
inventory: &mut CaptureInventory,
) -> io::Result<Option<(String, Value)>> {
let Some(key) = program.capture_key() else {
return Ok(None);
};
let prefix = program
.args()
.iter()
.position(|a| program.python_script().is_some_and(|s| a == s.as_os_str()) || a == "-m")
.ok_or_else(|| io::Error::other("Python invocation lacks script"))?;
let probe = "import sys,sysconfig,json; print(json.dumps({'executable':sys.executable,'paths':sys.path,'stdlib':sysconfig.get_path('stdlib'),'version':str(sys.version_info.major)+'.'+str(sys.version_info.minor)}))";
let output = Command::new(program.program())
.envs(program.environment())
.args(&program.args()[..prefix])
.arg("-c")
.arg(probe)
.output()?;
if !output.status.success() {
return Err(io::Error::other(
"Python environment introspection failed before capture",
));
}
let info: Value = serde_json::from_slice(&output.stdout).map_err(io::Error::other)?;
let home_key = format!("reproduction/python/{key}");
let home = root.join(&home_key);
let mut paths = Vec::new();
let stdlib = PathBuf::from(
info["stdlib"]
.as_str()
.ok_or_else(|| io::Error::other("missing Python stdlib"))?,
);
let version = info["version"].as_str().unwrap();
let target = format!("{home_key}/lib/python{version}");
capture_software_tree(store, &stdlib, &target, &root.join(&target), inventory)?;
paths.push(root.join(&target));
for (i, path) in info["paths"]
.as_array()
.ok_or_else(|| io::Error::other("invalid Python paths"))?
.iter()
.enumerate()
{
let Some(path) = path.as_str().filter(|s| !s.is_empty()) else {
continue;
};
let path = Path::new(path);
if !path.is_dir() {
continue;
}
if let Ok(relative) = path.strip_prefix(&stdlib) {
let captured = home.join(format!("lib/python{version}")).join(relative);
if !paths.contains(&captured) {
paths.push(captured);
}
continue;
}
let target = format!("{home_key}/search-{i}");
capture_software_tree(store, path, &target, &root.join(&target), inventory)?;
paths.push(root.join(&target));
}
let executable = Path::new(
info["executable"]
.as_str()
.ok_or_else(|| io::Error::other("missing Python executable"))?,
)
.canonicalize()?;
let binary_key = format!("{home_key}/bin/python");
capture_file(
store,
&executable,
&binary_key,
Some(&root.join(&binary_key)),
inventory,
ArtifactRole::Reproduction,
)?;
libraries(store, &executable, root, inventory)?;
let extensions = inventory
.keys()
.filter(|path| {
path.starts_with(&format!("{home_key}/"))
&& path
.rsplit('/')
.next()
.is_some_and(|name| name.contains(".so"))
})
.map(|path| root.join(path))
.collect::<Vec<_>>();
for extension in extensions {
libraries(store, &extension, root, inventory)?;
}
Ok(Some((
key.into(),
json!({"manager":"system","executable":root.join(binary_key),"search_paths":paths,"home":home}),
)))
}