Skip to main content

forgetop_core/
config.rs

1//! Persisted configuration: connections + per-section bindings, and the config store.
2//! Note: config NEVER contains secrets — only a `credential_ref` key into the secret store.
3
4use std::path::{Path, PathBuf};
5
6use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8
9use crate::domain::Section;
10use crate::error::Result;
11use crate::provider::Connection;
12
13#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
14pub struct PullRequestBinding {
15    /// Connections whose pull requests are aggregated into the PR list.
16    #[serde(default, skip_serializing_if = "Vec::is_empty")]
17    pub connection_ids: Vec<String>,
18    /// Legacy single-bind field; folded into `connection_ids` on read.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub connection_id: Option<String>,
21}
22
23#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
24pub struct WorkItemBinding {
25    #[serde(default, skip_serializing_if = "Vec::is_empty")]
26    pub connection_ids: Vec<String>,
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub connection_id: Option<String>,
29}
30
31/// Merges the multi-bind list with any legacy single id, de-duplicated.
32fn merged_ids(ids: &[String], legacy: &Option<String>) -> Vec<String> {
33    let mut out = ids.to_vec();
34    if let Some(c) = legacy {
35        if !out.contains(c) {
36            out.push(c.clone());
37        }
38    }
39    out
40}
41
42impl PullRequestBinding {
43    pub fn ids(&self) -> Vec<String> {
44        merged_ids(&self.connection_ids, &self.connection_id)
45    }
46}
47
48impl WorkItemBinding {
49    pub fn ids(&self) -> Vec<String> {
50        merged_ids(&self.connection_ids, &self.connection_id)
51    }
52}
53
54/// One connection feeding the Pipelines section, plus the pipelines subscribed from it.
55#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
56pub struct PipelineSubscription {
57    pub connection_id: String,
58    #[serde(default)]
59    pub definition_ids: Vec<String>,
60    #[serde(default)]
61    pub auto_discover_all: bool,
62}
63
64#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
65pub struct PipelineBinding {
66    #[serde(default)]
67    pub subscriptions: Vec<PipelineSubscription>,
68}
69
70#[derive(Debug, Clone, Default, Serialize, Deserialize)]
71pub struct UiState {
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub theme: Option<String>,
74    #[serde(default)]
75    pub active_section: Section,
76    /// Sections the user has hidden from the tab bar.
77    #[serde(default, skip_serializing_if = "Vec::is_empty")]
78    pub hidden_sections: Vec<Section>,
79    /// Work-item state names the user has hidden from the Work Items list
80    /// (provider-specific strings, e.g. "Done"). Anything not listed is shown.
81    #[serde(default, skip_serializing_if = "Vec::is_empty")]
82    pub hidden_work_item_states: Vec<String>,
83    /// Launchpad items the user has explicitly dismissed from Command Center's
84    /// "Needs you" list ("connection_id:item_id" keys, see launchpad::Entry::key).
85    #[serde(default, skip_serializing_if = "Vec::is_empty")]
86    pub dismissed_launchpad_items: Vec<String>,
87    /// Per-view sort column + direction. `None` = provider order.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub pr_sort: Option<SortPref>,
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub work_item_sort: Option<SortPref>,
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub pipeline_sort: Option<SortPref>,
94    /// How the Pipelines list is grouped: "pipeline" (default), "trigger", "branch",
95    /// or "off" for the ungrouped list. Unknown values fall back to the default.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub pipeline_group: Option<String>,
98    /// Which desktop notifications are enabled. Defaults to all on.
99    #[serde(default)]
100    pub notifications: NotificationPrefs,
101    /// Saved views per section (a named bundle of filter + sort + state).
102    #[serde(default, skip_serializing_if = "Vec::is_empty")]
103    pub pr_views: Vec<SavedView>,
104    #[serde(default, skip_serializing_if = "Vec::is_empty")]
105    pub work_item_views: Vec<SavedView>,
106    #[serde(default, skip_serializing_if = "Vec::is_empty")]
107    pub pipeline_views: Vec<SavedView>,
108}
109
110/// A named, saved bundle of a section's filter + sort + visible state.
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct SavedView {
113    pub name: String,
114    /// PR base filter: "all" / "mine" / "review" (Pull Requests only).
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub filter: Option<String>,
117    /// Quick-filter text applied to the list.
118    #[serde(default, skip_serializing_if = "String::is_empty")]
119    pub query: String,
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub sort: Option<SortPref>,
122    /// Hidden work-item states (Work Items only).
123    #[serde(default, skip_serializing_if = "Vec::is_empty")]
124    pub hidden_states: Vec<String>,
125}
126
127fn yes() -> bool {
128    true
129}
130
131/// Per-event desktop-notification opt-ins. Every event defaults to on.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
133pub struct NotificationPrefs {
134    #[serde(default = "yes")]
135    pub pipeline_failed: bool,
136    #[serde(default = "yes")]
137    pub review_requested: bool,
138    #[serde(default = "yes")]
139    pub pr_approved: bool,
140    #[serde(default = "yes")]
141    pub pr_changes_requested: bool,
142    #[serde(default = "yes")]
143    pub pipeline_approval_needed: bool,
144}
145
146impl Default for NotificationPrefs {
147    fn default() -> Self {
148        Self {
149            pipeline_failed: true,
150            review_requested: true,
151            pr_approved: true,
152            pr_changes_requested: true,
153            pipeline_approval_needed: true,
154        }
155    }
156}
157
158impl NotificationPrefs {
159    /// True if any event is enabled.
160    pub fn any(&self) -> bool {
161        self.pipeline_failed
162            || self.review_requested
163            || self.pr_approved
164            || self.pr_changes_requested
165            || self.pipeline_approval_needed
166    }
167}
168
169/// A saved sort: which column (by key) and whether descending.
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct SortPref {
172    pub key: String,
173    pub desc: bool,
174}
175
176/// Root persisted configuration.
177#[derive(Debug, Clone, Default, Serialize, Deserialize)]
178pub struct ForgetopConfig {
179    #[serde(default)]
180    pub connections: Vec<Connection>,
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub pull_requests: Option<PullRequestBinding>,
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub work_items: Option<WorkItemBinding>,
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub pipelines: Option<PipelineBinding>,
187    #[serde(default)]
188    pub ui: UiState,
189}
190
191impl ForgetopConfig {
192    pub fn find_connection(&self, id: &str) -> Option<&Connection> {
193        self.connections.iter().find(|c| c.id == id)
194    }
195}
196
197/// Loads and saves the root configuration.
198#[async_trait]
199pub trait ConfigStore: Send + Sync {
200    async fn load(&self) -> Result<ForgetopConfig>;
201    async fn save(&self, config: &ForgetopConfig) -> Result<()>;
202}
203
204/// Resolves the on-disk config path: `$XDG_CONFIG_HOME/forgetop/config.json` (or the
205/// platform config dir).
206pub fn default_config_path() -> PathBuf {
207    let base = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
208    base.join("forgetop").join("config.json")
209}
210
211/// JSON-file config store with atomic (temp + rename) writes.
212pub struct JsonConfigStore {
213    path: PathBuf,
214}
215
216impl JsonConfigStore {
217    pub fn new(path: impl Into<PathBuf>) -> Self {
218        Self { path: path.into() }
219    }
220
221    pub fn at_default_path() -> Self {
222        Self::new(default_config_path())
223    }
224}
225
226#[async_trait]
227impl ConfigStore for JsonConfigStore {
228    async fn load(&self) -> Result<ForgetopConfig> {
229        if !self.path.exists() {
230            return Ok(ForgetopConfig::default());
231        }
232        let bytes = tokio::fs::read(&self.path).await?;
233        Ok(serde_json::from_slice(&bytes)?)
234    }
235
236    async fn save(&self, config: &ForgetopConfig) -> Result<()> {
237        if let Some(dir) = self.path.parent() {
238            tokio::fs::create_dir_all(dir).await?;
239        }
240        let json = serde_json::to_vec_pretty(config)?;
241        // Write to a temp file then rename so a crash mid-write can't corrupt config.
242        let tmp = with_extension(&self.path, "tmp");
243        tokio::fs::write(&tmp, &json).await?;
244        tokio::fs::rename(&tmp, &self.path).await?;
245        Ok(())
246    }
247}
248
249fn with_extension(path: &Path, ext: &str) -> PathBuf {
250    let mut p = path.to_path_buf();
251    p.set_extension(ext);
252    p
253}
254
255/// Non-persistent config store (used for `--demo` and tests).
256pub struct InMemoryConfigStore {
257    config: std::sync::Mutex<ForgetopConfig>,
258}
259
260impl InMemoryConfigStore {
261    pub fn new(seed: ForgetopConfig) -> Self {
262        Self { config: std::sync::Mutex::new(seed) }
263    }
264}
265
266impl Default for InMemoryConfigStore {
267    fn default() -> Self {
268        Self::new(ForgetopConfig::default())
269    }
270}
271
272#[async_trait]
273impl ConfigStore for InMemoryConfigStore {
274    async fn load(&self) -> Result<ForgetopConfig> {
275        Ok(self.config.lock().unwrap().clone())
276    }
277    async fn save(&self, config: &ForgetopConfig) -> Result<()> {
278        *self.config.lock().unwrap() = config.clone();
279        Ok(())
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    /// The whole `Option<Vec<String>>` choice rests on this: `Some([])` and `None` must survive a
288    /// real JSON round-trip as *different* values. If an emptied scope came back as `None`, the
289    /// factory would fall back to the legacy single repository and silently refill a scope the
290    /// user had deliberately cleared. (The in-memory store clones rather than serializes, so it
291    /// cannot catch this — only going through JSON can.)
292    #[test]
293    fn an_emptied_repository_scope_survives_json_as_a_different_value_from_never_set() {
294        use crate::domain::ProviderType;
295        use crate::provider::Connection;
296
297        let conn = |repo_scope: Option<Vec<String>>| Connection {
298            id: "gh".into(),
299            provider_type: ProviderType::GitHub,
300            display_name: "GitHub".into(),
301            base_url: None,
302            organization: None,
303            project: None,
304            repository: Some("acme/pay".into()),
305            username: None,
306            credential_ref: None,
307            repo_scope,
308        };
309        let roundtrip = |c: &Connection| -> Connection { serde_json::from_str(&serde_json::to_string(c).unwrap()).unwrap() };
310
311        // Never set → the field isn't written at all, and reads back as absent.
312        let never = conn(None);
313        assert!(!serde_json::to_string(&never).unwrap().contains("repo_scope"));
314        assert_eq!(roundtrip(&never).repo_scope, None);
315        assert_eq!(never.resolve_repo_scope(|| never.repository.clone()), vec!["acme/pay".to_string()]);
316
317        // Chose none → written as `[]`, reads back as `Some([])`, and stays empty.
318        let emptied = conn(Some(vec![]));
319        assert!(serde_json::to_string(&emptied).unwrap().contains(r#""repo_scope":[]"#));
320        let read = roundtrip(&emptied);
321        assert_eq!(read.repo_scope, Some(vec![]));
322        assert!(read.resolve_repo_scope(|| read.repository.clone()).is_empty(), "an emptied scope must not refill");
323
324        // Chose some → exactly those come back.
325        let chosen = conn(Some(vec!["acme/ledger".into()]));
326        assert_eq!(roundtrip(&chosen).repo_scope, Some(vec!["acme/ledger".to_string()]));
327    }
328
329    #[test]
330    fn binding_ids_merge_legacy_and_dedup() {
331        // Legacy single-bind config deserializes and migrates via ids().
332        let legacy: PullRequestBinding = serde_json::from_str(r#"{"connection_id":"gh-1"}"#).unwrap();
333        assert_eq!(legacy.ids(), vec!["gh-1".to_string()]);
334
335        // Multi-bind with a legacy id already present is de-duplicated.
336        let b = PullRequestBinding { connection_ids: vec!["a".into(), "b".into()], connection_id: Some("a".into()) };
337        assert_eq!(b.ids(), vec!["a".to_string(), "b".to_string()]);
338
339        // New writes only serialize the list, not the legacy field.
340        let json = serde_json::to_string(&PullRequestBinding { connection_ids: vec!["x".into()], connection_id: None }).unwrap();
341        assert_eq!(json, r#"{"connection_ids":["x"]}"#);
342    }
343}