Skip to main content

subspace_shell/
product.rs

1//! Product configuration paths and headless alias validation.
2
3use std::path::PathBuf;
4
5use gpui_kit::{App, Global};
6use serde_json::Value;
7use subspace_product::{
8    OsKind, PlatformEnv, ProductContext, ProductDescriptor, product_data_name, validate_product,
9};
10
11pub(crate) struct ProductFiles {
12    pub config: PathBuf,
13    pub state: PathBuf,
14}
15
16impl Global for ProductFiles {}
17
18impl ProductFiles {
19    pub(crate) fn for_context(context: &ProductContext) -> Self {
20        Self {
21            config: config_file(context),
22            state: preference_file(context),
23        }
24    }
25}
26
27/// Existing cross-platform config first, then native config. New settings use
28/// the native root when available, preserving Subspace's existing location.
29pub fn config_file(context: &ProductContext) -> PathBuf {
30    let roots = context.product_roots();
31    roots
32        .product_roots()
33        .into_iter()
34        .map(|root| root.join("config.json"))
35        .find(|file| file.exists())
36        .unwrap_or_else(|| {
37            roots
38                .native
39                .unwrap_or(roots.cross_platform)
40                .join("config.json")
41        })
42}
43
44fn preference_file(context: &ProductContext) -> PathBuf {
45    state_directory(&context.env, context.product.binary_name.as_str()).join("state.json")
46}
47
48/// The product's own state folder, which holds `state.json`.
49pub(crate) fn state_directory(env: &PlatformEnv, binary_name: &str) -> PathBuf {
50    let base = match env.os {
51        OsKind::Linux => env
52            .xdg_state_home
53            .clone()
54            .unwrap_or_else(|| env.home.join(".local/state")),
55        OsKind::Macos => env.home.join("Library/Application Support"),
56        OsKind::Windows => env
57            .local_app_data
58            .clone()
59            .unwrap_or_else(|| env.home.join("AppData/Local")),
60    };
61    base.join(product_data_name(binary_name))
62}
63
64/// Loads only product command aliases before CLI or desktop startup. Service
65/// credentials are not read here.
66pub fn prepare_context(
67    mut descriptor: ProductDescriptor,
68    version: &str,
69) -> Result<ProductContext, String> {
70    let env = PlatformEnv::from_process().map_err(|error| error.to_string())?;
71    let mut context = context_with_env(&mut descriptor, env)?;
72    context.version = version.to_owned();
73    Ok(context)
74}
75
76fn context_with_env(
77    descriptor: &mut ProductDescriptor,
78    env: PlatformEnv,
79) -> Result<ProductContext, String> {
80    let validated = validate_product(descriptor).map_err(|error| error.to_string())?;
81    let context = ProductContext::new(validated, env);
82    let file = config_file(&context);
83    if let Some(value) = load_alias_file(&file)? {
84        apply_aliases(descriptor, &value)?;
85    }
86    let product = validate_product(descriptor).map_err(|error| error.to_string())?;
87    Ok(ProductContext::new(product, context.env))
88}
89
90fn load_alias_file(file: &std::path::Path) -> Result<Option<Value>, String> {
91    let text = match std::fs::read_to_string(file) {
92        Ok(text) => text,
93        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
94        Err(error) => {
95            return Err(format!(
96                "cannot read product configuration {}: {error}",
97                file.display()
98            ));
99        }
100    };
101    serde_json::from_str(&text)
102        .map(Some)
103        .map_err(|_| format!("invalid product configuration JSON: {}", file.display()))
104}
105
106fn apply_aliases(descriptor: &mut ProductDescriptor, value: &Value) -> Result<(), String> {
107    let Some(aliases) = value.pointer("/commands/aliases") else {
108        return Ok(());
109    };
110    let aliases = aliases
111        .as_object()
112        .ok_or("commands.aliases must be an object")?;
113    for (id, value) in aliases {
114        let board = descriptor
115            .boards
116            .iter_mut()
117            .find(|board| &board.id == id)
118            .ok_or_else(|| format!("commands.aliases names an excluded board: {id}"))?;
119        let values = value
120            .as_array()
121            .ok_or_else(|| format!("commands.aliases.{id} must be an array"))?;
122        for value in values {
123            let alias = value
124                .as_str()
125                .ok_or_else(|| format!("commands.aliases.{id} must contain strings"))?;
126            board.aliases.push(alias.to_owned());
127        }
128    }
129    Ok(())
130}
131
132pub(crate) fn gui_config_file(cx: &App) -> PathBuf {
133    cx.global::<ProductFiles>().config.clone()
134}
135
136#[cfg(test)]
137mod tests {
138    use super::{
139        ProductFiles, apply_aliases, config_file, context_with_env, load_alias_file,
140        preference_file,
141    };
142    use subspace_product::{OsKind, PlatformEnv, ProductContext, fixture, validate_product};
143
144    #[test]
145    fn product_aliases_validate_collisions_and_excluded_boards() {
146        let mut descriptor = fixture::descriptor();
147        apply_aliases(
148            &mut descriptor,
149            &serde_json::json!({"commands":{"aliases":{"github":["gh"]}}}),
150        )
151        .unwrap();
152        assert!(
153            validate_product(&descriptor)
154                .unwrap()
155                .board_for_command("gh")
156                .is_some()
157        );
158        apply_aliases(
159            &mut descriptor,
160            &serde_json::json!({"commands":{"aliases":{"github":["github"]}}}),
161        )
162        .unwrap();
163        assert!(validate_product(&descriptor).is_err());
164        assert!(
165            apply_aliases(
166                &mut descriptor,
167                &serde_json::json!({"commands":{"aliases":{"missing":["m"]}}})
168            )
169            .unwrap_err()
170            .contains("excluded board")
171        );
172    }
173
174    #[test]
175    fn gui_files_are_product_specific() {
176        let root = tempfile::tempdir().unwrap();
177        let known = fixture::products().unwrap();
178        let env = PlatformEnv {
179            os: OsKind::Macos,
180            home: root.path().to_owned(),
181            xdg_config_home: None,
182            xdg_state_home: None,
183            app_data: None,
184            local_app_data: None,
185        };
186        let context = ProductContext::new(known[0].clone(), env.clone());
187        let files = ProductFiles::for_context(&context);
188        assert_eq!(files.state, preference_file(&context));
189        assert_eq!(files.config, config_file(&context));
190        let name = subspace_product::product_data_name("subspace");
191        assert!(
192            preference_file(&context).ends_with(format!("Application Support/{name}/state.json"))
193        );
194        assert!(config_file(&context).ends_with(format!("Application Support/{name}/config.json")));
195        assert!(!root.path().join("Library").exists());
196        let mut descriptor = fixture::descriptor();
197        let reloaded = context_with_env(&mut descriptor, env).unwrap();
198        assert_eq!(reloaded.product.id.as_str(), "subspace");
199        assert!(!root.path().join("Library").exists());
200    }
201
202    #[test]
203    fn alias_loader_does_not_repeat_configuration_contents() {
204        let root = tempfile::tempdir().unwrap();
205        let file = root.path().join("config.json");
206        assert_eq!(load_alias_file(&file).unwrap(), None);
207        std::fs::write(&file, "a-secret-that-is-not-json").unwrap();
208        let error = load_alias_file(&file).unwrap_err();
209        assert!(error.contains("invalid product configuration JSON"));
210        assert!(!error.contains("a-secret"));
211        std::fs::write(&file, "{}").unwrap();
212        assert_eq!(load_alias_file(&file).unwrap(), Some(serde_json::json!({})));
213    }
214}