use std::{
cell::OnceCell,
path::{Path, PathBuf},
};
use same_same::{
Cache, Command, Comparer, ConfiguredFormatter, Detail, Detect, Format, Input, Method, Note,
Verdict,
};
use super::{Layout, Pair, words};
use crate::{
RepoPath, RepoRoot,
config::{FormatConfig, FormatRule},
source,
};
pub const CACHE_FOLDER: &str = "same-same";
pub struct Session {
root: RepoRoot,
on: bool,
built: OnceCell<Built>,
}
struct Built {
comparer: Comparer,
cache: Cache,
origin: RepoPath,
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("on", &self.on)
.finish_non_exhaustive()
}
}
impl Drop for Session {
fn drop(&mut self) {
if let Some(built) = self.built.get() {
let _ = built.cache.flush();
}
}
}
impl Session {
pub fn new(root: &RepoRoot, on: bool) -> Session {
Session {
root: root.clone(),
on,
built: OnceCell::new(),
}
}
pub fn identity(&self) -> String {
let built = self
.built
.get_or_init(|| self.build(&crate::config::format_config(&self.root)));
let identities: Vec<String> = built
.comparer
.normalisers()
.iter()
.map(|(id, _)| id.to_string())
.collect();
if identities.is_empty() {
"none".to_string()
} else {
identities.join(",")
}
}
pub fn settle(&self, config: &FormatConfig, pairs: &[Pair]) -> Layout {
let mut layout = Layout::default();
if pairs.is_empty() {
return layout;
}
let built = self.built.get_or_init(|| self.build(config));
let wholes: Vec<Option<String>> = pairs
.iter()
.map(|p| {
let source = p.source.as_ref()?;
let range = source.range.as_ref()?;
let text = source::load_text(&self.root, &source.path).ok()?;
(lines_of(&text, range) == p.expected).then_some(text)
})
.collect();
let inputs: Vec<(Input<'_>, Input<'_>)> = pairs
.iter()
.zip(&wholes)
.map(|(p, whole)| inputs(p, whole.as_deref()))
.collect();
let mut answers = built.comparer.compare_all(&inputs, Detail::Verdict);
let different: Vec<usize> = (0..answers.len())
.filter(|&i| {
let answer = &answers[i];
let normalised = matches!(answer.method, Method::Normaliser { .. })
|| answer.notes.iter().any(|note| {
matches!(
note,
Note::NormaliserUnavailable { .. } | Note::NormaliserCannot { .. }
)
});
!normalised && matches!(answer.verdict, Verdict::Different | Verdict::Unknown)
})
.collect();
if !different.is_empty() {
let again: Vec<(Input<'_>, Input<'_>)> =
different.iter().map(|&i| inputs[i].clone()).collect();
for (i, answer) in different
.into_iter()
.zip(built.comparer.compare_all(&again, Detail::FirstPlace))
{
answers[i] = answer;
}
}
for ((pair, answer), whole) in pairs.iter().zip(&answers).zip(&wholes) {
let reading = words::reading(pair, answer, whole.is_some(), config.same, &built.origin);
layout.insert(pair.clone(), reading);
}
layout
}
fn build(&self, config: &FormatConfig) -> Built {
let root = self.root.as_path().to_path_buf();
let cache = if self.on {
crate::cache::ensure_dir(&self.root).map_or_else(
|_| Cache::memory(),
|dir| Cache::folder(&dir.join(CACHE_FOLDER)),
)
} else {
Cache::memory()
};
let builder = Comparer::builder()
.formats(Format::ALL.iter().copied())
.cache(cache.clone());
let config_file = crate::config::config_path();
let builder = match &config.rule {
Some(FormatRule::Formatter {
formatter,
config: file,
settings,
plugins,
}) => builder.formatter(ConfiguredFormatter {
formatter: *formatter,
files: vec!["*".into()],
overrides: false,
root: root.clone(),
program: None,
config: file.as_ref().map(PathBuf::from),
settings: *settings,
plugins: plugins.clone(),
timeout: config.timeout,
}),
Some(FormatRule::Command { argv, config: file }) => builder.command(Command {
argv: command_line(&root, argv),
files: vec!["*".into()],
overrides: false,
timeout: config.timeout,
version_argv: None,
settings: file.as_deref().and_then(|f| settings_file(&root, f)),
}),
None => builder,
};
let (builder, origin) = if config.detect {
let origin = match &config.rule {
Some(_) => config_file,
None => detected_origin(&root).unwrap_or(config_file),
};
let builder = builder.detect(Detect {
root: root.clone(),
timeout: config.timeout,
});
(builder, origin)
} else {
(builder, config_file)
};
let comparer = builder
.build()
.expect("sokf compiles every format of same-same");
Built {
comparer,
cache,
origin,
}
}
}
fn detected_origin(root: &Path) -> Option<RepoPath> {
let found = same_same::detected(root)?;
let root = std::path::absolute(root).ok()?;
let parts: Vec<String> = found
.found_by
.strip_prefix(&root)
.ok()?
.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
RepoPath::parse(&format!("/{}", parts.join("/")))
}
fn inputs<'a>(pair: &'a Pair, whole: Option<&'a str>) -> (Input<'a>, Input<'a>) {
let expected = match (whole, pair.source.as_ref().and_then(|s| s.range.clone())) {
(Some(whole), Some(range)) => Input::bytes(whole.as_bytes(), &pair.name).lines(range),
_ => mark(
Input::bytes(pair.expected.as_bytes(), &pair.name),
pair.fragment,
),
};
let actual = mark(
Input::bytes(pair.actual.as_bytes(), &pair.name),
pair.fragment,
);
(expected, actual)
}
fn mark(input: Input<'_>, fragment: bool) -> Input<'_> {
if fragment { input.fragment() } else { input }
}
fn lines_of(text: &str, range: &std::ops::Range<u32>) -> String {
let start = usize::try_from(range.start).unwrap_or(usize::MAX);
let end = usize::try_from(range.end).unwrap_or(usize::MAX);
text.lines()
.enumerate()
.filter(|(i, _)| (start..end).contains(&(i + 1)))
.fold(String::new(), |mut out, (_, line)| {
out.push_str(line);
out.push('\n');
out
})
}
fn command_line(root: &Path, argv: &[String]) -> Vec<String> {
let mut argv = argv.to_vec();
if let Some(program) = argv.first_mut() {
if program.contains(['/', '\\']) {
if !program.starts_with(['/', '\\']) && Path::new(program.as_str()).is_relative() {
*program = root.join(&*program).to_string_lossy().into_owned();
}
} else if let Some(found) = program_in(&root.join("node_modules").join(".bin"), program)
.filter(|found| inside(root, found))
{
*program = found.to_string_lossy().into_owned();
}
}
argv
}
fn inside(root: &Path, path: &Path) -> bool {
std::fs::canonicalize(root)
.ok()
.zip(std::fs::canonicalize(path).ok())
.is_some_and(|(root, path)| path.starts_with(root))
}
fn program_in(folder: &Path, name: &str) -> Option<PathBuf> {
const ENDINGS: [&str; 3] = ["exe", "cmd", "bat"];
let ending = Path::new(name).extension();
let ended =
ending.is_some_and(|ending| ENDINGS.iter().any(|of| ending.eq_ignore_ascii_case(of)));
let mut candidates: Vec<PathBuf> = Vec::new();
if cfg!(windows) && !ended {
candidates.extend(ENDINGS.iter().map(|of| folder.join(format!("{name}.{of}"))));
}
if !cfg!(windows) || ending.is_some() {
candidates.push(folder.join(name));
}
candidates.into_iter().find(|path| is_program(path))
}
fn is_program(path: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::metadata(path)
.is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
{
path.is_file()
}
}
fn settings_file(root: &Path, file: &str) -> Option<(String, String)> {
let text = std::fs::read_to_string(root.join(file)).ok()?;
let name = Path::new(file).file_name()?.to_string_lossy().into_owned();
Some((name, text))
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use crate::test_support::{fresh_dir, write};
#[test]
fn a_bare_program_runs_from_node_modules_only_where_it_is_a_program() {
use std::os::unix::fs::PermissionsExt as _;
let dir = fresh_dir("command-line");
let argv = |program: &str| vec![program.to_string(), "{files}".to_string()];
write(&dir, "node_modules/.bin/fmt", "#!/bin/sh\n");
assert_eq!(
command_line(&dir, &argv("fmt"))[0],
"fmt",
"a file that isn't a program"
);
let bin = dir.join("node_modules/.bin/fmt");
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(command_line(&dir, &argv("fmt"))[0], bin.to_string_lossy());
let outside = fresh_dir("command-line-outside");
write(&outside, "fmt", "#!/bin/sh\n");
std::fs::set_permissions(outside.join("fmt"), std::fs::Permissions::from_mode(0o755))
.unwrap();
std::os::unix::fs::symlink(outside.join("fmt"), dir.join("node_modules/.bin/out")).unwrap();
assert_eq!(
command_line(&dir, &argv("out"))[0],
"out",
"a link out of the repository"
);
std::fs::remove_dir_all(&outside).unwrap();
std::fs::create_dir_all(dir.join("node_modules/.bin/dir")).unwrap();
assert_eq!(command_line(&dir, &argv("dir"))[0], "dir", "a folder");
assert_eq!(
command_line(&dir, &argv("./tools/fmt.sh"))[0],
dir.join("./tools/fmt.sh").to_string_lossy()
);
assert_eq!(command_line(&dir, &argv("/usr/bin/fmt"))[0], "/usr/bin/fmt");
std::fs::remove_dir_all(&dir).unwrap();
}
}