Skip to main content

subspace_core/settings/
repos.rs

1//! Checked immediate edits of the favourite repositories (`repos`), the one
2//! list GitHub, Copilot Agents, Actions and the agent tools share.
3
4use serde_json::Value;
5
6use super::{SettingsError, SettingsFile};
7use crate::config;
8
9impl SettingsFile {
10    /// Immediately writes `repos` as the saved list, in order. Every other
11    /// value and unknown key in the file is kept, and the file stays
12    /// owner-only. A file changed since it was opened is refused as stale.
13    pub fn update_repos(&mut self, repos: &[String]) -> Result<(), SettingsError> {
14        validate(repos)?;
15        self.check_current()?;
16        let mut root = self.root.clone();
17        root.insert("repos".into(), values(repos));
18        self.write_root(root)
19    }
20}
21
22/// Each entry must be `owner/name`.
23pub(super) fn validate(repos: &[String]) -> Result<(), SettingsError> {
24    if repos.iter().any(|repo| !config::is_repo(repo)) {
25        return Err(SettingsError::Validation {
26            field: "repos",
27            reason: "each entry must be owner/name",
28        });
29    }
30    Ok(())
31}
32
33/// The saved JSON array, each name once without regard to case.
34pub(super) fn values(repos: &[String]) -> Value {
35    let mut unique: Vec<&String> = Vec::new();
36    for repo in repos {
37        if !unique.iter().any(|known| known.eq_ignore_ascii_case(repo)) {
38            unique.push(repo);
39        }
40    }
41    unique
42        .into_iter()
43        .cloned()
44        .map(Value::String)
45        .collect::<Vec<_>>()
46        .into()
47}
48
49#[cfg(test)]
50mod tests {
51    use crate::settings::{SettingsError, SettingsFile};
52    use serde_json::{Value, json};
53    use std::fs;
54
55    fn saved(path: &std::path::Path) -> Value {
56        serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap()
57    }
58
59    #[test]
60    fn favourites_save_alone_and_keep_every_other_value() {
61        let directory = tempfile::tempdir().unwrap();
62        let path = directory.path().join("config.json");
63        fs::write(
64            &path,
65            r#"{"repos":["acme/web"],"github":{"token":"gh"},"unknown":{"keep":7}}"#,
66        )
67        .unwrap();
68        let mut file = SettingsFile::open(&path).unwrap();
69        let list = ["acme/web".to_owned(), "acme/api".into(), "ACME/API".into()];
70        file.update_repos(&list).unwrap();
71        let root = saved(&path);
72        assert_eq!(root["repos"], json!(["acme/web", "acme/api"]));
73        assert_eq!(root["github"]["token"], "gh");
74        assert_eq!(root["unknown"]["keep"], 7);
75        assert!(root.get("mcp").is_none(), "nothing else is written");
76        assert_eq!(file.values().repos, ["acme/web", "acme/api"]);
77        file.update_repos(&[]).unwrap();
78        assert_eq!(saved(&path)["repos"], json!([]));
79        assert_eq!(
80            crate::config::load(&path).0.github.token.unwrap().expose(),
81            "gh"
82        );
83    }
84
85    #[cfg(unix)]
86    #[test]
87    fn a_new_or_shared_file_becomes_owner_only() {
88        use std::os::unix::fs::PermissionsExt;
89        let directory = tempfile::tempdir().unwrap();
90        for existing in [false, true] {
91            let path = directory.path().join(format!("{existing}.json"));
92            if existing {
93                fs::write(&path, "{}").unwrap();
94                fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
95            }
96            let mut file = SettingsFile::open(&path).unwrap();
97            file.update_repos(&["acme/web".to_owned()]).unwrap();
98            let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
99            assert_eq!(mode, 0o600, "existing: {existing}");
100        }
101    }
102
103    #[test]
104    fn invalid_names_and_stale_files_write_nothing() {
105        let directory = tempfile::tempdir().unwrap();
106        let path = directory.path().join("config.json");
107        fs::write(&path, r#"{"repos":["acme/web"]}"#).unwrap();
108        let mut file = SettingsFile::open(&path).unwrap();
109        assert!(matches!(
110            file.update_repos(&["not a repo".to_owned()]),
111            Err(SettingsError::Validation { field: "repos", .. })
112        ));
113        fs::write(&path, r#"{"external":true}"#).unwrap();
114        assert!(matches!(
115            file.update_repos(&["acme/api".to_owned()]),
116            Err(SettingsError::Stale)
117        ));
118        assert_eq!(saved(&path), json!({"external": true}));
119    }
120}