use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use crumbkit::{Failure, Recovery};
use toml_edit::{Array, ArrayOfTables, DocumentMut, InlineTable, Item, RawString, Table, Value};
use crate::codes::{CLIPPY_INVALID, CLIPPY_UNWRITABLE};
use crate::files;
#[cfg(test)]
mod tests;
pub(crate) const BANNED: [&str; 4] = [
"std::env::var",
"std::env::var_os",
"std::env::vars",
"std::env::vars_os",
];
const REASON: &str = "read the environment through the struct that derives starmap::Env, whose variables starmap.toml declares";
const KEY: &str = "disallowed-methods";
const NAMES: [&str; 2] = [".clippy.toml", "clippy.toml"];
const MAX_BYTES: usize = 256 * 1024;
#[derive(Debug)]
pub(crate) struct Ban {
pub(crate) file: PathBuf,
pub(crate) exists: bool,
pub(crate) missing: Vec<&'static str>,
document: DocumentMut,
}
impl Ban {
pub(crate) fn write(mut self, spec: &Path) -> Result<(), ClippyFailure> {
if self.missing.is_empty() {
return Ok(());
}
add(&mut self.document, &self.missing);
let text = self.document.to_string();
let written = if self.exists {
files::replace(&self.file, &text)
} else {
files::write_new(&self.file, &text)
};
written.map_err(|error| ClippyFailure::Unwritable {
file: self.file.display().to_string(),
spec: spec.display().to_string(),
error,
})
}
fn sentence(&self, dry_run: bool) -> String {
let file = self.file.display();
let methods = list(&self.missing);
match (self.missing.is_empty(), self.exists, dry_run) {
(true, _, _) => format!("{file} already disallows {}.", list(&BANNED)),
(false, true, false) => {
format!("Added {KEY} entries to {file} for {methods}.")
}
(false, false, false) => format!("Wrote {file} with {KEY} entries for {methods}."),
(false, true, true) => {
format!("init would add {KEY} entries to {file} for {methods}.")
}
(false, false, true) => {
format!("init would write {file} with {KEY} entries for {methods}.")
}
}
}
}
pub(crate) fn sentences(bans: &[Ban], dry_run: bool) -> String {
if bans.is_empty() {
return "init read no .rs file, so it wrote no clippy.toml.".to_owned();
}
let lines: Vec<String> = bans.iter().map(|ban| ban.sentence(dry_run)).collect();
lines.join("\n")
}
pub(crate) fn list(methods: &[&str]) -> String {
match methods.split_last() {
None => String::new(),
Some((last, [])) => (*last).to_owned(),
Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
}
}
pub(crate) fn open(spec: &Path, dirs: &[PathBuf]) -> Vec<Result<Ban, ClippyFailure>> {
let beside = spec.parent().unwrap_or(Path::new(""));
let base = canonical(beside);
let mut crates: Vec<PathBuf> = Vec::new();
for dir in dirs {
let dir = canonical(dir);
let krate = dir
.ancestors()
.find(|above| files::is_file(&above.join("Cargo.toml")))
.unwrap_or(&base);
if !crates.iter().any(|found| found == krate) {
crates.push(krate.to_path_buf());
}
}
let mut found: Vec<(PathBuf, bool)> = Vec::new();
for krate in crates {
let (file, exists) = find(&krate, &base);
let file = match file.strip_prefix(&base) {
Ok(below) => beside.join(below),
Err(_) => file,
};
if !found.contains(&(file.clone(), exists)) {
found.push((file, exists));
}
}
found
.into_iter()
.map(|(file, exists)| read(file, exists))
.collect()
}
fn canonical(dir: &Path) -> PathBuf {
let dir = if dir.as_os_str().is_empty() {
Path::new(".")
} else {
dir
};
files::canonical(dir).unwrap_or_else(|_| dir.to_path_buf())
}
fn find(krate: &Path, base: &Path) -> (PathBuf, bool) {
let root = krate
.ancestors()
.find(|above| files::exists(&above.join(".git")))
.or_else(|| krate.ancestors().find(|above| is_workspace(above)))
.unwrap_or(krate);
let found = krate
.ancestors()
.take_while(|above| above.starts_with(root))
.flat_map(|dir| NAMES.map(|name| dir.join(name)))
.find(|file| files::is_file(file));
match found {
Some(file) => (files::canonical(&file).unwrap_or(file), true),
None => {
let beside_spec = krate.starts_with(base) && base.starts_with(root);
let dir = if beside_spec { base } else { krate };
(dir.join("clippy.toml"), false)
}
}
}
fn is_workspace(dir: &Path) -> bool {
files::read_capped(&dir.join("Cargo.toml"), MAX_BYTES)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.and_then(|text| text.parse::<DocumentMut>().ok())
.is_some_and(|manifest| manifest.get("workspace").is_some_and(Item::is_table_like))
}
fn read(file: PathBuf, exists: bool) -> Result<Ban, ClippyFailure> {
if !exists {
return Ok(Ban {
file,
exists,
missing: BANNED.to_vec(),
document: DocumentMut::new(),
});
}
let invalid = |reason: String| ClippyFailure::Invalid {
file: file.display().to_string(),
reason,
};
let bytes = files::read_capped(&file, MAX_BYTES + 1)
.map_err(|error| invalid(format!("cannot be read: {error}")))?;
if bytes.len() > MAX_BYTES {
return Err(invalid("is over 256 KiB".to_owned()));
}
let text = String::from_utf8(bytes).map_err(|_| invalid("is not UTF-8 text".to_owned()))?;
let document: DocumentMut = text.parse().map_err(|error: toml_edit::TomlError| {
invalid(format!("is not valid TOML: {}", error.message()))
})?;
let missing = missing(&document)
.ok_or_else(|| invalid(format!("sets {KEY} to a value that is not an array")))?;
Ok(Ban {
file,
exists,
missing,
document,
})
}
fn missing(document: &DocumentMut) -> Option<Vec<&'static str>> {
let listed: Vec<&str> = match document.get(KEY) {
None => Vec::new(),
Some(Item::Value(Value::Array(array))) => array
.iter()
.filter_map(|entry| match entry {
Value::InlineTable(table) => table.get("path").and_then(Value::as_str),
entry => entry.as_str(),
})
.collect(),
Some(Item::ArrayOfTables(tables)) => tables
.iter()
.filter_map(|table| table.get("path").and_then(Item::as_str))
.collect(),
Some(_) => return None,
};
Some(
BANNED
.into_iter()
.filter(|method| !listed.contains(method))
.collect(),
)
}
fn add(document: &mut DocumentMut, methods: &[&'static str]) {
if methods.is_empty() {
return;
}
match document
.entry(KEY)
.or_insert_with(|| Item::Value(Value::Array(Array::new())))
{
Item::Value(Value::Array(array)) => extend(array, methods),
Item::ArrayOfTables(tables) => append(tables, methods),
_ => {}
}
}
fn extend(array: &mut Array, methods: &[&'static str]) {
let indent = array
.iter()
.last()
.map_or(Some("\n ".to_owned()), |last| {
let prefix = last.decor().prefix()?.as_str()?;
let (_, spaces) = prefix.rsplit_once('\n')?;
Some(format!("\n{spaces}"))
});
let table = |method: &str| {
let mut table = InlineTable::new();
table.insert("path", method.into());
table.insert("reason", REASON.into());
Value::InlineTable(table)
};
let Some(indent) = indent else {
for method in methods {
array.push(table(method));
}
return;
};
let mut tail = String::new();
if let Some(last) = array.iter_mut().last() {
tail.push_str(text(last.decor().suffix()));
last.decor_mut().set_suffix("");
}
tail.push_str(text(Some(array.trailing())));
let (beside, below) = tail.split_once('\n').unwrap_or((&tail, ""));
let mut prefix = format!("{}{indent}", beside.trim_end());
for method in methods {
let mut entry = table(method);
entry.decor_mut().set_prefix(prefix.as_str());
array.push_formatted(entry);
prefix.clone_from(&indent);
}
array.set_trailing_comma(true);
array.set_trailing(format!("\n{below}"));
}
fn text(raw: Option<&RawString>) -> &str {
raw.and_then(RawString::as_str).unwrap_or_default()
}
fn append(tables: &mut ArrayOfTables, methods: &[&'static str]) {
for method in methods {
let mut table = Table::new();
table.insert("path", toml_edit::value(*method));
table.insert("reason", toml_edit::value(REASON));
tables.push(table);
}
}
#[derive(Debug, Failure)]
pub(crate) enum ClippyFailure {
#[failure(
code = CLIPPY_INVALID,
hint = "make {file} a readable file of at most 256 KiB that holds valid TOML whose disallowed-methods is an array",
field(file = file.as_str()),
)]
Invalid {
file: String,
reason: String,
},
#[failure(
code = CLIPPY_UNWRITABLE,
hint = "make {file} and its directory writable, then run starmap init --spec {spec} --clippy",
alternative = Recovery::Hint(format!("add the entries to {file} by hand, as starmap check lists them")),
field(file = file.as_str()),
)]
Unwritable {
file: String,
spec: String,
error: io::Error,
},
}
impl fmt::Display for ClippyFailure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Invalid { file, reason } => write!(formatter, "{file} {reason}"),
Self::Unwritable { file, .. } => write!(formatter, "{file} cannot be written"),
}
}
}
impl std::error::Error for ClippyFailure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Unwritable { error, .. } => Some(error),
Self::Invalid { .. } => None,
}
}
}