use std::path::{Path, PathBuf};
use rustc_hash::FxHashSet;
use super::FallowConfig;
pub(super) struct LocalValue {
pub(super) path: PathBuf,
pub(super) inside: bool,
pub(super) value: serde_json::Value,
}
impl LocalValue {
pub(super) fn new(path: &Path, inside: bool, value: &serde_json::Value) -> Self {
Self {
path: path.to_path_buf(),
inside,
value: value.clone(),
}
}
}
pub(super) fn has_outside(values: &[LocalValue]) -> bool {
values.iter().any(|value| !value.inside)
}
#[derive(Debug, Clone, Default)]
pub struct OutsideKeys {
paths: FxHashSet<String>,
leaves: FxHashSet<String>,
files: Vec<PathBuf>,
}
impl OutsideKeys {
pub(super) fn from_values(values: &[LocalValue]) -> Self {
let mut keys = Self::default();
for value in values.iter().filter(|value| !value.inside) {
keys.files.push(value.path.clone());
keys.collect(String::new(), &value.value);
}
keys
}
fn collect(&mut self, prefix: String, value: &serde_json::Value) {
let Some(map) = value.as_object() else {
if !prefix.is_empty() {
self.leaves.insert(prefix);
}
return;
};
for (key, child) in map {
let path = if prefix.is_empty() {
key.clone()
} else {
format!("{prefix}.{key}")
};
self.paths.insert(path.clone());
self.collect(path, child);
}
}
pub(super) fn covers(&self, field: &str) -> bool {
let key = field
.split(['[', ' ', ':'])
.next()
.unwrap_or(field)
.trim_end_matches('.');
if key.is_empty() || self.files.is_empty() {
return false;
}
if self.paths.contains(key) {
return true;
}
let mut end = key.len();
while let Some(dot) = key[..end].rfind('.') {
if self.leaves.contains(&key[..dot]) {
return true;
}
end = dot;
}
false
}
pub(super) fn file_list(&self) -> String {
self.files
.iter()
.map(|path| path.display().to_string())
.collect::<Vec<_>>()
.join(", ")
}
pub(super) fn redact(&self, message: String) -> String {
let field = message
.split([' ', ':'])
.next()
.unwrap_or_default()
.to_owned();
if self.covers(&field) {
self.field_message(&field)
} else {
message
}
}
pub(super) fn field_message(&self, field: &str) -> String {
format!(
"{field}: a value from a config file outside the project ({}) is not valid. \
The text of a file outside the project is not shown",
self.file_list()
)
}
}
pub(super) fn merged_error(path: &Path, values: &[LocalValue]) -> miette::Report {
for value in values.iter().filter(|value| value.inside) {
if let Err(error) = serde_json::from_value::<FallowConfig>(value.value.clone()) {
return miette::miette!(
"{} in {}",
crate::parse_error::describe_json(&error),
value.path.display()
);
}
}
let outside: Vec<String> = values
.iter()
.filter(|value| !value.inside)
.map(|value| value.path.display().to_string())
.collect();
miette::miette!(
"invalid config in {}: a file of its extends chain outside the project does not match the config schema ({}). The text of a file outside the project is not shown",
path.display(),
outside.join(", ")
)
}
pub type TrackedLinkProbe = fn(&Path) -> Option<bool>;
static TRACKED_LINK_PROBE: std::sync::OnceLock<TrackedLinkProbe> = std::sync::OnceLock::new();
pub fn set_tracked_link_probe(probe: TrackedLinkProbe) {
let _ = TRACKED_LINK_PROBE.set(probe);
}
pub(super) fn git_tracks(path: &Path) -> Option<bool> {
let dir = dunce::canonicalize(path.parent()?).ok()?;
crate::project_read::project_checkout_top(&dir)?;
TRACKED_LINK_PROBE.get().and_then(|probe| probe(path))
}
#[cfg(all(test, unix))]
pub fn test_tracked_link_probe(path: &std::path::Path) -> Option<bool> {
let dir = dunce::canonicalize(path.parent()?).ok()?;
let output = std::process::Command::new("git")
.arg("-C")
.arg(&dir)
.env("GIT_CEILING_DIRECTORIES", dir.parent()?)
.args(["--literal-pathspecs", "ls-files", "-z", "--"])
.arg(path.file_name()?)
.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE")
.stderr(std::process::Stdio::null())
.output()
.ok()?;
output.status.success().then_some(!output.stdout.is_empty())
}