use std::{
collections::BTreeSet,
ffi::OsString,
fs,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
time::{Duration, Instant},
};
use super::{preset::Formatter, sample::sample};
use crate::{RepoRoot, temp_dir::TempDir};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Form(String),
Failed,
Hung(Duration),
Skipped,
Unsettled(Fault),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Fault {
NoSample,
Hang,
Sample,
Broken,
}
impl Fault {
pub fn stops(self) -> bool {
self != Fault::NoSample
}
}
pub fn program(root: &RepoRoot, name: &str) -> Option<PathBuf> {
if name.contains('/') || name.contains(std::path::MAIN_SEPARATOR) {
let path = Path::new(name);
let path = if path.is_absolute() {
path.to_path_buf()
} else {
root.as_path().join(path)
};
return path.is_file().then_some(path);
}
let bin = root.as_path().join("node_modules").join(".bin");
let dirs = std::iter::once(bin).chain(
std::env::var_os("PATH")
.map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
.unwrap_or_default(),
);
for dir in dirs {
for candidate in candidates(&dir, name) {
if candidate.is_file() {
return Some(candidate);
}
}
}
None
}
fn candidates(dir: &Path, name: &str) -> Vec<PathBuf> {
if cfg!(windows) && Path::new(name).extension().is_none() {
["exe", "cmd", "bat"]
.iter()
.map(|ext| dir.join(format!("{name}.{ext}")))
.collect()
} else {
vec![dir.join(name)]
}
}
pub fn version(
root: &RepoRoot,
path: &Path,
package: Option<&str>,
limit: Duration,
) -> Result<Option<String>, String> {
if let Some(package) = package
&& let Some(v) = package_version(root, path, package)
{
return Ok(Some(format!("{package}@{v}")));
}
let mut cmd = command(path);
cmd.current_dir(std::env::temp_dir()).arg("--version");
let Ok(out) = run(cmd, Some(limit)) else {
return Ok(None);
};
if out.timed_out {
return Err(format!(
"`{} --version` ran for longer than the limit",
path.display()
));
}
if !out.success {
return Ok(None);
}
let text = if out.stdout.trim().is_empty() {
out.stderr
} else {
out.stdout
};
Ok(Some(text.trim().to_string()))
}
pub fn package_version(root: &RepoRoot, path: &Path, package: &str) -> Option<String> {
let named = |file: &Path| -> Option<String> {
let value: serde_json::Value =
serde_json::from_str(&fs::read_to_string(file).ok()?).ok()?;
(value.get("name").and_then(|n| n.as_str()) == Some(package))
.then(|| value.get("version")?.as_str().map(str::to_string))
.flatten()
};
let real = fs::canonicalize(path).ok();
real.iter()
.flat_map(|r| r.ancestors().skip(1).take(5))
.find_map(|dir| named(&dir.join("package.json")))
.or_else(|| {
named(
&root
.as_path()
.join("node_modules")
.join(package)
.join("package.json"),
)
})
}
pub fn format(
formatter: &Formatter,
program: &Path,
texts: &[(&str, &str)],
others: &[Vec<usize>],
limit: Duration,
) -> Result<Vec<Outcome>, String> {
let dir = TempDir::new("format").map_err(|e| format!("no temporary directory: {e}"))?;
let settings = dir.path().join(&formatter.settings_file);
let empty = dir.path().join("sokf-empty-ignore");
write(&settings, &formatter.settings)?;
write(&empty, "")?;
let names: Vec<String> = texts
.iter()
.enumerate()
.map(|(i, (ext, _))| format!("{i}.{ext}"))
.collect();
for (name, (_, text)) in names.iter().zip(texts) {
write(&dir.path().join(name), text)?;
}
let all: Vec<&str> = names.iter().map(String::as_str).collect();
let run_on = |files: &[&str]| {
run_on(
formatter,
program,
dir.path(),
(&settings, &empty),
files,
limit,
)
};
let first = run_on(&all)?;
let read = |name: &str| fs::read_to_string(dir.path().join(name)).ok();
if first.success {
return Ok(names
.iter()
.map(|n| read(n).map_or(Outcome::Failed, Outcome::Form))
.collect());
}
let mut outcomes: Vec<Option<Outcome>> = names
.iter()
.zip(texts)
.map(|(name, (_, text))| {
(!first.timed_out)
.then(|| read(name))
.flatten()
.filter(|f| f != text)
.map(Outcome::Form)
})
.collect();
let rest = match settle_alone(dir.path(), texts, others, &mut outcomes, limit, run_on) {
Ok(()) => Fault::Hang,
Err(_) => Fault::Broken,
};
Ok(outcomes
.into_iter()
.map(|o| o.unwrap_or(Outcome::Unsettled(rest)))
.collect())
}
fn settle_alone(
dir: &Path,
texts: &[(&str, &str)],
others: &[Vec<usize>],
outcomes: &mut [Option<Outcome>],
limit: Duration,
run_on: impl Fn(&[&str]) -> Result<Output, String>,
) -> Result<(), String> {
let exts: BTreeSet<&str> = texts
.iter()
.zip(outcomes.iter())
.filter(|(_, o)| o.is_none())
.map(|((ext, _), _)| *ext)
.collect();
if !samples_pass(dir, &exts, &run_on)? {
for o in outcomes.iter_mut().filter(|o| o.is_none()) {
*o = Some(Outcome::Unsettled(Fault::Sample));
}
return Ok(());
}
for i in 0..texts.len() {
if outcomes[i].is_some() {
continue;
}
if !others[i].is_empty()
&& others[i]
.iter()
.all(|&j| outcomes[j] == Some(Outcome::Failed))
{
outcomes[i] = Some(Outcome::Skipped);
continue;
}
let (ext, text) = texts[i];
let alone = format!("{i}-alone.{ext}");
write(&dir.join(&alone), text)?;
let one = run_on(&[&alone])?;
outcomes[i] = Some(if one.success {
fs::read_to_string(dir.join(&alone)).map_or(Outcome::Failed, Outcome::Form)
} else if sample(ext).is_some() {
if one.timed_out {
Outcome::Hung(limit)
} else {
Outcome::Failed
}
} else if one.timed_out {
Outcome::Unsettled(Fault::Hang)
} else {
Outcome::Unsettled(Fault::NoSample)
});
if one.timed_out {
break;
}
}
Ok(())
}
fn samples_pass(
dir: &Path,
exts: &BTreeSet<&str>,
run_on: impl Fn(&[&str]) -> Result<Output, String>,
) -> Result<bool, String> {
let mut files = Vec::new();
for ext in exts {
if let Some(text) = sample(ext) {
let name = format!("sample.{ext}");
write(&dir.join(&name), text)?;
files.push(name);
}
}
if files.is_empty() {
return Ok(true);
}
let files: Vec<&str> = files.iter().map(String::as_str).collect();
Ok(run_on(&files)?.success)
}
fn write(path: &Path, text: &str) -> Result<(), String> {
fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))
}
fn run_on(
formatter: &Formatter,
program: &Path,
dir: &Path,
(settings, empty): (&Path, &Path),
files: &[&str],
limit: Duration,
) -> Result<Output, String> {
let mut cmd = command(program);
cmd.current_dir(dir)
.stdout(Stdio::null())
.stderr(Stdio::null());
for arg in &formatter.args {
if arg == "{files}" {
cmd.args(files);
} else {
cmd.arg(fill(arg, settings, empty));
}
}
run(cmd, Some(limit)).map_err(|e| format!("`{}` doesn't start: {e}", formatter.program))
}
fn fill(arg: &str, settings: &Path, empty: &Path) -> OsString {
arg.replace("{settings}", &settings.to_string_lossy())
.replace("{empty}", &empty.to_string_lossy())
.into()
}
pub(crate) fn command(path: &Path) -> Command {
let mut cmd = Command::new(path);
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
for (key, _) in std::env::vars_os() {
if key.to_string_lossy().starts_with("GIT_") {
cmd.env_remove(key);
}
}
cmd
}
#[derive(Debug)]
struct Output {
success: bool,
timed_out: bool,
stdout: String,
stderr: String,
}
fn run(mut cmd: Command, limit: Option<Duration>) -> std::io::Result<Output> {
let mut child = cmd.spawn()?;
let stdout = drain(child.stdout.take());
let stderr = drain(child.stderr.take());
let start = Instant::now();
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if limit.is_some_and(|l| start.elapsed() > l) {
stop(&mut child);
return Ok(Output {
success: false,
timed_out: true,
stdout: String::new(),
stderr: String::new(),
});
}
std::thread::sleep(Duration::from_millis(2));
};
let left = limit.map_or(Duration::from_secs(1), |l| {
l.saturating_sub(start.elapsed())
});
let deadline = Instant::now()
+ left
.max(Duration::from_millis(100))
.min(Duration::from_hours(24));
let read = |rx: std::sync::mpsc::Receiver<String>| {
rx.recv_timeout(deadline.saturating_duration_since(Instant::now()))
.unwrap_or_default()
};
Ok(Output {
success: status.success(),
timed_out: false,
stdout: read(stdout),
stderr: read(stderr),
})
}
fn stop(child: &mut Child) {
let _ = child.kill();
let _ = child.wait();
}
fn drain<R: std::io::Read + Send + 'static>(pipe: Option<R>) -> std::sync::mpsc::Receiver<String> {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut text = String::new();
if let Some(mut pipe) = pipe {
let mut bytes = Vec::new();
let _ = pipe.read_to_end(&mut bytes);
text = String::from_utf8_lossy(&bytes).into_owned();
}
let _ = tx.send(text);
});
rx
}