Skip to main content

dort_core/
profiles.rs

1use crate::{Error, Result, model::base_profiles, platform::Platform};
2use serde::{Deserialize, Serialize};
3use std::collections::{BTreeMap, BTreeSet};
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6#[serde(deny_unknown_fields)]
7pub struct Profiles {
8    #[serde(default)]
9    pub available: Vec<String>,
10    #[serde(default = "base_profiles")]
11    pub default: Vec<String>,
12    #[serde(default)]
13    pub platform: BTreeMap<Platform, Vec<String>>,
14}
15
16impl Default for Profiles {
17    fn default() -> Self {
18        Self {
19            available: vec![],
20            default: base_profiles(),
21            platform: BTreeMap::new(),
22        }
23    }
24}
25
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28pub enum Choice {
29    #[default]
30    Defaults,
31    On,
32    Off,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
36#[serde(rename_all = "snake_case")]
37pub enum Reason {
38    Base,
39    Temporary,
40    Saved,
41    Legacy,
42    Platform,
43    RepositoryDefault,
44    NotDefault,
45}
46
47impl Reason {
48    pub fn label(self) -> &'static str {
49        match self {
50            Self::Base => "always on",
51            Self::Temporary => "temporary for this run",
52            Self::Saved => "saved choice",
53            Self::Legacy => "legacy local setting",
54            Self::Platform => "platform default",
55            Self::RepositoryDefault => "repository default",
56            Self::NotDefault => "not a default",
57        }
58    }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
62pub struct Row {
63    pub name: String,
64    pub on: bool,
65    pub reason: Reason,
66    pub choice: Choice,
67}
68
69impl Choice {
70    pub fn label(self) -> &'static str {
71        match self {
72            Self::Defaults => "Use defaults",
73            Self::On => "On",
74            Self::Off => "Off",
75        }
76    }
77}
78
79impl Row {
80    pub fn label(&self) -> String {
81        format!(
82            "{}: {} ({})",
83            self.name,
84            if self.on { "On" } else { "Off" },
85            self.reason.label()
86        )
87    }
88}
89
90pub fn active(rows: &[Row]) -> BTreeSet<String> {
91    rows.iter()
92        .filter(|row| row.on)
93        .map(|row| row.name.clone())
94        .collect()
95}
96
97impl Profiles {
98    pub fn known(&self) -> BTreeSet<String> {
99        self.available
100            .iter()
101            .cloned()
102            .chain(["base".into()])
103            .collect()
104    }
105
106    pub fn resolve(&self, platform: Platform, local: &[String]) -> Result<BTreeSet<String>> {
107        Ok(active(&self.rows(
108            platform,
109            local,
110            &BTreeMap::new(),
111            &[],
112        )?))
113    }
114
115    pub fn rows(
116        &self,
117        platform: Platform,
118        legacy: &[String],
119        saved: &BTreeMap<String, Choice>,
120        temporary: &[String],
121    ) -> Result<Vec<Row>> {
122        let known = self.known();
123        let platform_defaults = self.platform.get(&platform);
124        let unknown: BTreeSet<_> = self
125            .default
126            .iter()
127            .chain(platform_defaults.into_iter().flatten())
128            .chain(legacy)
129            .chain(temporary)
130            .filter(|name| !known.contains(*name))
131            .cloned()
132            .collect();
133        if !unknown.is_empty() {
134            return Err(Error::Invalid(format!(
135                "unknown active profiles: {}",
136                unknown.into_iter().collect::<Vec<_>>().join(", ")
137            )));
138        }
139        Ok(known
140            .into_iter()
141            .map(|name| {
142                let choice = saved.get(&name).copied().unwrap_or_default();
143                let (on, reason) = if name == "base" {
144                    (true, Reason::Base)
145                } else if temporary.contains(&name) {
146                    (true, Reason::Temporary)
147                } else if choice != Choice::Defaults {
148                    (choice == Choice::On, Reason::Saved)
149                } else if !saved.contains_key(&name) && legacy.contains(&name) {
150                    (true, Reason::Legacy)
151                } else if platform_defaults.is_some_and(|names| names.contains(&name)) {
152                    (true, Reason::Platform)
153                } else if self.default.contains(&name) {
154                    (true, Reason::RepositoryDefault)
155                } else {
156                    (false, Reason::NotDefault)
157                };
158                Row {
159                    name,
160                    on,
161                    reason,
162                    choice,
163                }
164            })
165            .collect())
166    }
167}
168
169pub fn selected(profiles: &[String], active: &BTreeSet<String>) -> bool {
170    profiles.iter().any(|p| active.contains(p))
171}