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