1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
18use std::path::{Path, PathBuf};
19
20use serde::{Deserialize, Serialize};
21
22use crate::apply::ApplyEnv;
23use crate::apply::import::{self, Candidate, ScanFilter, Source, source_key};
24use crate::apply::ledger::Ledger;
25use crate::apply::render::DesiredState;
26use crate::apply::write_atomic;
27use crate::error::{CoreError, ErrorCode};
28use crate::fs::Fs;
29use crate::model::applied::Scope;
30use crate::store::Store;
31
32pub const SEEN_FILE: &str = "unmanaged-seen.json";
34pub(crate) const SEEN_SCHEMA: u32 = 1;
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Finding {
39 pub id: String,
41 pub client: &'static str,
42 pub scope: Scope,
43 pub project_id: Option<String>,
44 pub project_root: Option<PathBuf>,
46 pub name: String,
47 pub file: PathBuf,
48}
49
50pub fn finding_id(source: &Source, name: &str) -> String {
52 format!("{}/{name}", source.key())
53}
54
55pub fn findings(candidates: &[Candidate]) -> Vec<Finding> {
57 let mut out = Vec::new();
58 for candidate in candidates {
59 for source in &candidate.sources {
60 out.push(Finding {
61 id: finding_id(source, &candidate.name),
62 client: source.client,
63 scope: source.scope,
64 project_id: source.project.as_ref().map(|p| p.id.clone()),
65 project_root: source.project.as_ref().map(|p| p.root.clone()),
66 name: candidate.name.clone(),
67 file: source.file.clone(),
68 });
69 }
70 }
71 out
72}
73
74pub fn scan_findings(
77 ax: &ApplyEnv<'_>,
78 desired: &DesiredState,
79 ledger: &Ledger,
80 filter: &ScanFilter,
81) -> Result<(Vec<Finding>, Vec<CoreError>), CoreError> {
82 let mut by_name: Vec<Vec<Finding>> = Vec::new();
84 let mut index: HashMap<String, usize> = HashMap::new();
85 let mut ids: HashSet<String> = HashSet::new();
86 let mut warnings = Vec::new();
87 import::walk(ax, desired, ledger, filter, &mut warnings, &mut |found| {
88 let project_id = found.project.map(|project| project.id.as_str());
89 let key = source_key(
90 found.spec.id,
91 found.slot.as_deref(),
92 found.target.scope,
93 project_id,
94 );
95 let id = format!("{key}/{}", found.name);
96 if !ids.insert(id.clone()) {
97 return Ok(());
98 }
99 let finding = Finding {
100 id,
101 client: found.spec.id,
102 scope: found.target.scope,
103 project_id: project_id.map(str::to_owned),
104 project_root: found.project.map(|project| project.root.clone()),
105 name: found.name,
106 file: found.target.file.clone(),
107 };
108 match index.get(&finding.name) {
109 Some(&at) => by_name[at].push(finding),
110 None => {
111 index.insert(finding.name.clone(), by_name.len());
112 by_name.push(vec![finding]);
113 }
114 }
115 Ok(())
116 })?;
117 Ok((by_name.into_iter().flatten().collect(), warnings))
118}
119
120pub fn store_findings(
123 store: Option<&Store<'_>>,
124 ax: &ApplyEnv<'_>,
125 filter: &ScanFilter,
126) -> Result<(Vec<Finding>, Vec<CoreError>), CoreError> {
127 let (desired, ledger) = import::store_inputs(store, ax)?;
128 scan_findings(ax, &desired, &ledger, filter)
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct Group {
134 pub client: &'static str,
135 pub scope: Scope,
136 pub project_id: Option<String>,
137 pub project_root: Option<PathBuf>,
138 pub files: Vec<PathBuf>,
140 pub entries: Vec<(Finding, bool)>,
142}
143
144pub fn groups(findings: Vec<Finding>, seen: &Seen) -> Vec<Group> {
148 type Key = (&'static str, u8, Option<String>);
149 let rank = |scope: Scope| match scope {
150 Scope::User => 0,
151 Scope::Project => 1,
152 Scope::ProjectLocal => 2,
153 };
154 let mut map: BTreeMap<Key, Group> = BTreeMap::new();
155 for finding in findings {
156 let key = (
157 finding.client,
158 rank(finding.scope),
159 finding.project_id.clone(),
160 );
161 let group = map.entry(key).or_insert_with(|| Group {
162 client: finding.client,
163 scope: finding.scope,
164 project_id: finding.project_id.clone(),
165 project_root: finding.project_root.clone(),
166 files: Vec::new(),
167 entries: Vec::new(),
168 });
169 if !group.files.contains(&finding.file) {
170 group.files.push(finding.file.clone());
171 }
172 let new = !seen.contains(&finding.id);
173 group.entries.push((finding, new));
174 }
175 let mut groups: Vec<Group> = map.into_values().collect();
176 for group in &mut groups {
177 group.entries.sort_by(|a, b| a.0.name.cmp(&b.0.name));
178 }
179 groups
180}
181
182#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
184pub struct Seen {
185 schema: u32,
186 #[serde(default)]
187 ids: BTreeSet<String>,
188}
189
190impl Seen {
191 pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
193 let path = state_dir.join(SEEN_FILE);
194 if !fs.exists(&path) {
195 return Ok(Self {
196 schema: SEEN_SCHEMA,
197 ids: BTreeSet::new(),
198 });
199 }
200 let text = fs.read_to_string(&path).map_err(|err| {
201 CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(&path)
202 })?;
203 let seen: Self = serde_json::from_str(&text).map_err(|err| {
204 CoreError::new(
205 ErrorCode::ParseError,
206 format!("the file does not parse: {err}"),
207 )
208 .with_path(&path)
209 })?;
210 if seen.schema != SEEN_SCHEMA {
211 return Err(CoreError::new(
212 ErrorCode::UnsupportedSchema,
213 format!("schema {} is not read by this build", seen.schema),
214 )
215 .with_path(&path));
216 }
217 Ok(seen)
218 }
219
220 pub fn contains(&self, id: &str) -> bool {
221 self.ids.contains(id)
222 }
223
224 pub fn acknowledge(
227 &mut self,
228 fs: &dyn Fs,
229 state_dir: &Path,
230 ids: &[String],
231 ) -> Result<usize, CoreError> {
232 let added = ids
233 .iter()
234 .filter(|id| self.ids.insert((*id).clone()))
235 .count();
236 if added == 0 {
237 return Ok(0);
238 }
239 self.schema = SEEN_SCHEMA;
240 let mut text = serde_json::to_string_pretty(self).map_err(|err| {
241 CoreError::new(ErrorCode::InvalidValue, format!("cannot serialize: {err}"))
242 })?;
243 text.push('\n');
244 fs.create_dir_all(state_dir).map_err(|err| {
245 CoreError::new(
246 ErrorCode::IoError,
247 format!("cannot create directory: {err}"),
248 )
249 .with_path(state_dir)
250 })?;
251 write_atomic(fs, &state_dir.join(SEEN_FILE), text.as_bytes())?;
252 Ok(added)
253 }
254}