subspace_shell/
product.rs1use 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
19pub(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
46pub(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
71pub 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).join("state.json")
90}
91
92pub(crate) fn state_directory(env: &PlatformEnv) -> PathBuf {
95 let base = match env.os {
96 OsKind::Linux => env
97 .xdg_state_home
98 .clone()
99 .unwrap_or_else(|| env.home.join(".local/state")),
100 OsKind::Macos => env.home.join("Library/Application Support"),
101 OsKind::Windows => env
102 .local_app_data
103 .clone()
104 .unwrap_or_else(|| env.home.join("AppData/Local")),
105 };
106 base.join(product_data_name())
107}
108
109pub fn prepare_context(
115 mut descriptor: ProductDescriptor,
116 version: &str,
117) -> Result<ProductContext, String> {
118 let product = validate_product(&descriptor).map_err(|error| error.to_string())?;
119 crate::startup::name_data_directory(product.binary_name.as_str())?;
120 let env = PlatformEnv::from_process().map_err(|error| error.to_string())?;
121 let mut context = context_with_env(&mut descriptor, env)?;
122 context.version = version.to_owned();
123 Ok(context)
124}
125
126fn context_with_env(
127 descriptor: &mut ProductDescriptor,
128 env: PlatformEnv,
129) -> Result<ProductContext, String> {
130 let validated = validate_product(descriptor).map_err(|error| error.to_string())?;
131 let context = ProductContext::new(validated, env);
132 let file = config_file(&context);
133 if let Some(value) = load_alias_file(&file)? {
134 apply_aliases(descriptor, &value)?;
135 }
136 let product = validate_product(descriptor).map_err(|error| error.to_string())?;
137 Ok(ProductContext::new(product, context.env))
138}
139
140fn load_alias_file(file: &std::path::Path) -> Result<Option<Value>, String> {
141 let text = match std::fs::read_to_string(file) {
142 Ok(text) => text,
143 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
144 Err(error) => {
145 return Err(format!(
146 "cannot read product configuration {}: {error}",
147 file.display()
148 ));
149 }
150 };
151 serde_json::from_str(&text)
152 .map(Some)
153 .map_err(|_| format!("invalid product configuration JSON: {}", file.display()))
154}
155
156fn apply_aliases(descriptor: &mut ProductDescriptor, value: &Value) -> Result<(), String> {
157 let Some(aliases) = value.pointer("/commands/aliases") else {
158 return Ok(());
159 };
160 let aliases = aliases
161 .as_object()
162 .ok_or("commands.aliases must be an object")?;
163 for (id, value) in aliases {
164 let board = descriptor
165 .boards
166 .iter_mut()
167 .find(|board| &board.id == id)
168 .ok_or_else(|| format!("commands.aliases names an excluded board: {id}"))?;
169 let values = value
170 .as_array()
171 .ok_or_else(|| format!("commands.aliases.{id} must be an array"))?;
172 for value in values {
173 let alias = value
174 .as_str()
175 .ok_or_else(|| format!("commands.aliases.{id} must contain strings"))?;
176 board.aliases.push(alias.to_owned());
177 }
178 }
179 Ok(())
180}
181
182pub(crate) fn gui_config_file(cx: &App) -> PathBuf {
183 cx.global::<ProductFiles>().config.clone()
184}
185
186#[cfg(test)]
187mod tests {
188 use super::{
189 DesktopName, ProductFiles, apply_aliases, config_file, context_with_env, load_alias_file,
190 preference_file,
191 };
192 use subspace_product::{OsKind, PlatformEnv, ProductContext, fixture, validate_product};
193
194 #[test]
195 fn desktop_name_can_be_prefixed_without_changing_the_bundle_name() {
196 let name = "Subspace";
197 assert_eq!(
198 DesktopName::new(name, Some("Example")).as_str(),
199 "Example Subspace"
200 );
201 assert_eq!(DesktopName::new(name, Some("")).as_str(), name);
202 assert_eq!(DesktopName::new(name, None).as_str(), name);
203 }
204
205 #[test]
206 fn product_aliases_validate_collisions_and_excluded_boards() {
207 let mut descriptor = fixture::descriptor();
208 apply_aliases(
209 &mut descriptor,
210 &serde_json::json!({"commands":{"aliases":{"github":["gh"]}}}),
211 )
212 .unwrap();
213 assert!(
214 validate_product(&descriptor)
215 .unwrap()
216 .board_for_command("gh")
217 .is_some()
218 );
219 apply_aliases(
220 &mut descriptor,
221 &serde_json::json!({"commands":{"aliases":{"github":["github"]}}}),
222 )
223 .unwrap();
224 assert!(validate_product(&descriptor).is_err());
225 assert!(
226 apply_aliases(
227 &mut descriptor,
228 &serde_json::json!({"commands":{"aliases":{"missing":["m"]}}})
229 )
230 .unwrap_err()
231 .contains("excluded board")
232 );
233 }
234
235 #[test]
236 fn gui_files_are_product_specific() {
237 let root = tempfile::tempdir().unwrap();
238 let known = fixture::products().unwrap();
239 let env = PlatformEnv {
240 os: OsKind::Macos,
241 home: root.path().to_owned(),
242 xdg_config_home: None,
243 xdg_state_home: None,
244 app_data: None,
245 local_app_data: None,
246 };
247 let context = ProductContext::new(known[0].clone(), env.clone());
248 let files = ProductFiles::for_context(&context);
249 assert_eq!(files.state, preference_file(&context));
250 assert_eq!(files.config, config_file(&context));
251 let name = subspace_product::product_data_name();
252 assert!(
253 preference_file(&context).ends_with(format!("Application Support/{name}/state.json"))
254 );
255 assert!(config_file(&context).ends_with(format!("Application Support/{name}/config.json")));
256 assert!(!root.path().join("Library").exists());
257 let mut descriptor = fixture::descriptor();
258 let reloaded = context_with_env(&mut descriptor, env).unwrap();
259 assert_eq!(reloaded.product.id.as_str(), "subspace");
260 assert!(!root.path().join("Library").exists());
261 }
262
263 #[test]
264 fn alias_loader_does_not_repeat_configuration_contents() {
265 let root = tempfile::tempdir().unwrap();
266 let file = root.path().join("config.json");
267 assert_eq!(load_alias_file(&file).unwrap(), None);
268 std::fs::write(&file, "a-secret-that-is-not-json").unwrap();
269 let error = load_alias_file(&file).unwrap_err();
270 assert!(error.contains("invalid product configuration JSON"));
271 assert!(!error.contains("a-secret"));
272 std::fs::write(&file, "{}").unwrap();
273 assert_eq!(load_alias_file(&file).unwrap(), Some(serde_json::json!({})));
274 }
275}