1use 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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
17 pub connection_ids: Vec<String>,
18 #[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
31fn 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#[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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
78 pub hidden_sections: Vec<Section>,
79 #[serde(default, skip_serializing_if = "Vec::is_empty")]
82 pub hidden_work_item_states: Vec<String>,
83 #[serde(default, skip_serializing_if = "Vec::is_empty")]
86 pub dismissed_launchpad_items: Vec<String>,
87 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub pipeline_group: Option<String>,
98 #[serde(default)]
100 pub notifications: NotificationPrefs,
101 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct SavedView {
113 pub name: String,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub filter: Option<String>,
117 #[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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
124 pub hidden_states: Vec<String>,
125}
126
127fn yes() -> bool {
128 true
129}
130
131#[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 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#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct SortPref {
172 pub key: String,
173 pub desc: bool,
174}
175
176#[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#[async_trait]
199pub trait ConfigStore: Send + Sync {
200 async fn load(&self) -> Result<ForgetopConfig>;
201 async fn save(&self, config: &ForgetopConfig) -> Result<()>;
202}
203
204pub 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
211pub 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 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
255pub 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 #[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 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 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 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 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 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 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}