1use std::collections::{BTreeMap, BTreeSet};
8
9use super::{Document, Model};
10use crate::{RepoPath, Spanned, Yaml};
11
12#[derive(Debug, Clone, PartialEq, Eq, Default)]
14pub enum Archived {
15 #[default]
17 None,
18 All,
21 States(Vec<(String, Vec<String>)>),
25}
26
27impl Archived {
28 pub fn of_schema(yaml: &Spanned) -> Archived {
33 if yaml.get("archived").and_then(Spanned::as_bool) == Some(true) {
36 let lifecycle = yaml
37 .get("lifecycle")
38 .and_then(Spanned::as_seq)
39 .is_some_and(|d| !d.is_empty());
40 return if lifecycle {
41 Archived::None
42 } else {
43 Archived::All
44 };
45 }
46 let dimensions: Vec<(String, Vec<String>)> = yaml
47 .get("lifecycle")
48 .and_then(Spanned::as_seq)
49 .unwrap_or(&[])
50 .iter()
51 .filter_map(|d| {
52 let key = d.get("key")?.as_str()?.to_string();
53 let states = d.get("archived")?.as_str_or_list()?;
54 Some((key, states))
55 })
56 .collect();
57 if dimensions.is_empty() {
58 Archived::None
59 } else {
60 Archived::States(dimensions)
61 }
62 }
63
64 pub fn encode(&self) -> String {
68 match self {
69 Archived::None => String::new(),
70 Archived::All => "*".to_string(),
71 Archived::States(dimensions) => dimensions
72 .iter()
73 .map(|(key, states)| format!("{key}\t{}", states.join("\t")))
74 .collect::<Vec<_>>()
75 .join("\n"),
76 }
77 }
78
79 pub fn decode(text: &str) -> Archived {
81 match text {
82 "" => Archived::None,
83 "*" => Archived::All,
84 _ => Archived::States(
85 text.lines()
86 .filter_map(|line| {
87 let mut parts = line.split('\t');
88 let key = parts.next()?.to_string();
89 Some((key, parts.map(str::to_string).collect()))
90 })
91 .collect(),
92 ),
93 }
94 }
95
96 pub fn holds(&self, values: &[(String, String)]) -> bool {
104 match self {
105 Archived::None => false,
106 Archived::All => true,
107 Archived::States(dimensions) => dimensions.iter().any(|(key, states)| {
108 values
109 .iter()
110 .find(|(k, _)| k == key)
111 .is_some_and(|(_, v)| states.contains(v))
112 }),
113 }
114 }
115}
116
117pub fn scalars(doc: &Document) -> Vec<(String, String)> {
124 scalars_of(doc.frontmatter.as_ref())
125}
126
127pub fn scalars_of(frontmatter: Option<&Spanned>) -> Vec<(String, String)> {
130 let Some(entries) = frontmatter.and_then(Spanned::as_map) else {
131 return Vec::new();
132 };
133 entries
134 .iter()
135 .filter(|(k, _)| !matches!(k.value.as_str(), "id" | "type" | "title" | "description"))
136 .filter_map(|(k, v)| {
137 let text = match &v.value {
138 Yaml::Str(s) => s.clone(),
139 Yaml::Int(i) => i.to_string(),
140 Yaml::Bool(b) => b.to_string(),
141 _ => return None,
142 };
143 Some((k.value.clone(), text))
144 })
145 .collect()
146}
147
148pub fn encode_scalars(scalars: &[(String, String)]) -> String {
152 scalars
153 .iter()
154 .map(|(k, v)| format!("{k}\t{}", v.replace(['\n', '\r'], " ")))
155 .collect::<Vec<_>>()
156 .join("\n")
157}
158
159pub fn decode_scalars(text: &str) -> Vec<(String, String)> {
162 text.lines()
163 .filter_map(|l| l.split_once('\t'))
164 .map(|(k, v)| (k.to_string(), v.to_string()))
165 .collect()
166}
167
168impl Model {
169 fn archive_rules(&self) -> BTreeMap<(usize, String), Archived> {
172 let mut rules = BTreeMap::new();
173 for (k, knowledge) in self.knowledges.iter().enumerate() {
174 let own = knowledge.schemas.iter();
177 let inherited = self.inherited(k).into_iter().map(|r| self.schema(r));
178 for schema in own.chain(inherited) {
179 if let Some(t) = &schema.type_const
180 && schema.archived != Archived::None
181 {
182 rules
183 .entry((k, t.clone()))
184 .or_insert_with(|| schema.archived.clone());
185 }
186 }
187 }
188 rules
189 }
190
191 pub fn is_archived(
195 &self,
196 knowledge: usize,
197 type_name: Option<&str>,
198 frontmatter: Option<&Spanned>,
199 ) -> bool {
200 let Some(type_name) = type_name else {
201 return false;
202 };
203 self.archive_rules()
204 .get(&(knowledge, type_name.to_string()))
205 .is_some_and(|rule| rule.holds(&scalars_of(frontmatter)))
206 }
207
208 pub fn archived_documents(&self) -> BTreeSet<RepoPath> {
214 let rules = self.archive_rules();
215 let mut out = BTreeSet::new();
216 if rules.is_empty() {
217 return out;
218 }
219 let mut held = BTreeSet::new();
220 for (k, doc) in self.documents() {
221 held.insert(doc.path.clone());
222 let Some(rule) = doc.type_name().and_then(|t| rules.get(&(k, t.to_string()))) else {
223 continue;
224 };
225 if rule.holds(&scalars(doc)) {
226 out.insert(doc.path.clone());
227 }
228 }
229 if let Some(fallback) = &self.fallback {
230 for ((k, type_name), rule) in &rules {
231 for (path, values) in fallback.scalars_of_type(*k, type_name) {
232 if held.contains(&path) {
233 continue;
234 }
235 if rule.holds(&values) {
236 out.insert(path);
237 }
238 }
239 }
240 }
241 out
242 }
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248
249 fn schema(text: &str) -> Spanned {
250 crate::yaml::parse(text, 1).unwrap()
251 }
252
253 #[test]
256 fn archived_reads_encodes_and_holds() {
257 let states = Archived::of_schema(&schema(
258 "lifecycle:\n - key: state\n states: [open, closed]\n archived: [closed]\n - key: kind\n states: [a]\n",
259 ));
260 assert_eq!(
261 states,
262 Archived::States(vec![("state".into(), vec!["closed".into()])])
263 );
264 assert_eq!(Archived::decode(&states.encode()), states);
265 let state = |v: &str| [("state".to_string(), v.to_string())];
266 assert!(states.holds(&state("closed")));
267 assert!(!states.holds(&state("open")));
268 assert!(!states.holds(&[]));
269 let all = Archived::of_schema(&schema("archived: true\n"));
270 assert_eq!(all, Archived::All);
271 assert_eq!(Archived::decode(&all.encode()), all);
272 assert!(all.holds(&[]));
273 assert_eq!(
276 Archived::of_schema(&schema("lifecycle: []\narchived: true\n")),
277 Archived::All
278 );
279 let none = Archived::of_schema(&schema("archived: false\n"));
280 assert_eq!(none, Archived::None);
281 assert_eq!(Archived::decode(&none.encode()), none);
282 assert!(!none.holds(&state("x")));
283 }
284
285 #[test]
286 fn scalars_keep_the_values_the_columns_do_not() {
287 let source = crate::Source::from_text(
288 RepoPath::parse("/k/a.md").unwrap(),
289 "---\ntype: A\nid: a\ntitle: T\nstate: closed\nseq: 3\ndone: true\ntags: [x]\n---\n\n# T\n",
290 );
291 let parsed = super::super::parse_source(&source, super::super::ParseMode::Document);
292 let doc = Document::new(source, parsed);
293 let values = scalars(&doc);
294 assert_eq!(
295 values,
296 vec![
297 ("state".to_string(), "closed".to_string()),
298 ("seq".to_string(), "3".to_string()),
299 ("done".to_string(), "true".to_string()),
300 ]
301 );
302 assert_eq!(decode_scalars(&encode_scalars(&values)), values);
303 }
304}