Skip to main content

databricks_tui/
config.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::path::PathBuf;
4
5/// Preferences remembered across sessions; written whenever the user
6/// changes one, best-effort.
7#[derive(Debug, Default, Clone, Serialize, Deserialize)]
8pub struct Config {
9    /// Theme id in the same kebab-case form the --theme flag takes.
10    pub theme: Option<String>,
11    /// Chosen SQL warehouse per profile: profile → (id, name).
12    #[serde(default)]
13    pub warehouses: HashMap<String, (String, String)>,
14    /// Pane ids in display order (missing ones append in default order).
15    #[serde(default)]
16    pub pane_order: Vec<String>,
17    /// Pane ids the user has hidden.
18    #[serde(default)]
19    pub hidden_panes: Vec<String>,
20    /// Favorited item keys per profile → pane id → item keys. The item key
21    /// is the ListItem id when present (job id, catalog full name), else name.
22    #[serde(default)]
23    pub favorites: HashMap<String, HashMap<String, Vec<String>>>,
24}
25
26fn path() -> Option<PathBuf> {
27    let home = std::env::var_os("HOME")?;
28    Some(
29        PathBuf::from(home)
30            .join(".config")
31            .join("databricks-tui")
32            .join("config.json"),
33    )
34}
35
36impl Config {
37    pub fn load() -> Self {
38        path()
39            .and_then(|p| std::fs::read_to_string(p).ok())
40            .and_then(|s| serde_json::from_str(&s).ok())
41            .unwrap_or_default()
42    }
43
44    pub fn save(&self) {
45        let Some(p) = path() else {
46            return;
47        };
48        if let Some(dir) = p.parent() {
49            let _ = std::fs::create_dir_all(dir);
50            restrict(dir, 0o700);
51        }
52        if let Ok(json) = serde_json::to_string_pretty(self) {
53            let _ = std::fs::write(&p, json);
54            restrict(&p, 0o600);
55        }
56    }
57}
58
59/// Owner-only permissions on files the app writes (no-op off Unix).
60pub fn restrict(path: &std::path::Path, mode: u32) {
61    #[cfg(unix)]
62    {
63        use std::os::unix::fs::PermissionsExt;
64        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
65    }
66    #[cfg(not(unix))]
67    let _ = (path, mode);
68}