use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::apply::ApplyEnv;
use crate::apply::import::{self, Candidate, ScanFilter, Source, source_key};
use crate::apply::ledger::Ledger;
use crate::apply::render::DesiredState;
use crate::apply::write_atomic;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::model::applied::Scope;
use crate::store::Store;
pub const SEEN_FILE: &str = "unmanaged-seen.json";
pub(crate) const SEEN_SCHEMA: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
pub id: String,
pub client: &'static str,
pub scope: Scope,
pub project_id: Option<String>,
pub project_root: Option<PathBuf>,
pub name: String,
pub file: PathBuf,
}
pub fn finding_id(source: &Source, name: &str) -> String {
format!("{}/{name}", source.key())
}
pub fn findings(candidates: &[Candidate]) -> Vec<Finding> {
let mut out = Vec::new();
for candidate in candidates {
for source in &candidate.sources {
out.push(Finding {
id: finding_id(source, &candidate.name),
client: source.client,
scope: source.scope,
project_id: source.project.as_ref().map(|p| p.id.clone()),
project_root: source.project.as_ref().map(|p| p.root.clone()),
name: candidate.name.clone(),
file: source.file.clone(),
});
}
}
out
}
pub fn scan_findings(
ax: &ApplyEnv<'_>,
desired: &DesiredState,
ledger: &Ledger,
filter: &ScanFilter,
) -> Result<(Vec<Finding>, Vec<CoreError>), CoreError> {
let mut by_name: Vec<Vec<Finding>> = Vec::new();
let mut index: HashMap<String, usize> = HashMap::new();
let mut ids: HashSet<String> = HashSet::new();
let mut warnings = Vec::new();
import::walk(ax, desired, ledger, filter, &mut warnings, &mut |found| {
let project_id = found.project.map(|project| project.id.as_str());
let key = source_key(
found.spec.id,
found.slot.as_deref(),
found.target.scope,
project_id,
);
let id = format!("{key}/{}", found.name);
if !ids.insert(id.clone()) {
return Ok(());
}
let finding = Finding {
id,
client: found.spec.id,
scope: found.target.scope,
project_id: project_id.map(str::to_owned),
project_root: found.project.map(|project| project.root.clone()),
name: found.name,
file: found.target.file.clone(),
};
match index.get(&finding.name) {
Some(&at) => by_name[at].push(finding),
None => {
index.insert(finding.name.clone(), by_name.len());
by_name.push(vec![finding]);
}
}
Ok(())
})?;
Ok((by_name.into_iter().flatten().collect(), warnings))
}
pub fn store_findings(
store: Option<&Store<'_>>,
ax: &ApplyEnv<'_>,
filter: &ScanFilter,
) -> Result<(Vec<Finding>, Vec<CoreError>), CoreError> {
let (desired, ledger) = import::store_inputs(store, ax)?;
scan_findings(ax, &desired, &ledger, filter)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Group {
pub client: &'static str,
pub scope: Scope,
pub project_id: Option<String>,
pub project_root: Option<PathBuf>,
pub files: Vec<PathBuf>,
pub entries: Vec<(Finding, bool)>,
}
pub fn groups(findings: Vec<Finding>, seen: &Seen) -> Vec<Group> {
type Key = (&'static str, u8, Option<String>);
let rank = |scope: Scope| match scope {
Scope::User => 0,
Scope::Project => 1,
Scope::ProjectLocal => 2,
};
let mut map: BTreeMap<Key, Group> = BTreeMap::new();
for finding in findings {
let key = (
finding.client,
rank(finding.scope),
finding.project_id.clone(),
);
let group = map.entry(key).or_insert_with(|| Group {
client: finding.client,
scope: finding.scope,
project_id: finding.project_id.clone(),
project_root: finding.project_root.clone(),
files: Vec::new(),
entries: Vec::new(),
});
if !group.files.contains(&finding.file) {
group.files.push(finding.file.clone());
}
let new = !seen.contains(&finding.id);
group.entries.push((finding, new));
}
let mut groups: Vec<Group> = map.into_values().collect();
for group in &mut groups {
group.entries.sort_by(|a, b| a.0.name.cmp(&b.0.name));
}
groups
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Seen {
schema: u32,
#[serde(default)]
ids: BTreeSet<String>,
}
impl Seen {
pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
let path = state_dir.join(SEEN_FILE);
if !fs.exists(&path) {
return Ok(Self {
schema: SEEN_SCHEMA,
ids: BTreeSet::new(),
});
}
let text = fs.read_to_string(&path).map_err(|err| {
CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(&path)
})?;
let seen: Self = serde_json::from_str(&text).map_err(|err| {
CoreError::new(
ErrorCode::ParseError,
format!("the file does not parse: {err}"),
)
.with_path(&path)
})?;
if seen.schema != SEEN_SCHEMA {
return Err(CoreError::new(
ErrorCode::UnsupportedSchema,
format!("schema {} is not read by this build", seen.schema),
)
.with_path(&path));
}
Ok(seen)
}
pub fn contains(&self, id: &str) -> bool {
self.ids.contains(id)
}
pub fn acknowledge(
&mut self,
fs: &dyn Fs,
state_dir: &Path,
ids: &[String],
) -> Result<usize, CoreError> {
let added = ids
.iter()
.filter(|id| self.ids.insert((*id).clone()))
.count();
if added == 0 {
return Ok(0);
}
self.schema = SEEN_SCHEMA;
let mut text = serde_json::to_string_pretty(self).map_err(|err| {
CoreError::new(ErrorCode::InvalidValue, format!("cannot serialize: {err}"))
})?;
text.push('\n');
fs.create_dir_all(state_dir).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot create directory: {err}"),
)
.with_path(state_dir)
})?;
write_atomic(fs, &state_dir.join(SEEN_FILE), text.as_bytes())?;
Ok(added)
}
}