subspace_shell/
product.rs1use 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
27pub 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
48pub(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
64pub fn prepare_context(
67 mut descriptor: ProductDescriptor,
68 version: &str,
69 subspace_version: &str,
70) -> Result<ProductContext, String> {
71 let env = PlatformEnv::from_process().map_err(|error| error.to_string())?;
72 let mut context = context_with_env(&mut descriptor, env)?;
73 context.version = version.to_owned();
74 context.subspace_version = subspace_version.to_owned();
75 Ok(context)
76}
77
78fn context_with_env(
79 descriptor: &mut ProductDescriptor,
80 env: PlatformEnv,
81) -> Result<ProductContext, String> {
82 let validated = validate_product(descriptor).map_err(|error| error.to_string())?;
83 let context = ProductContext::new(validated, env);
84 let file = config_file(&context);
85 if let Some(value) = load_alias_file(&file)? {
86 apply_aliases(descriptor, &value)?;
87 }
88 let product = validate_product(descriptor).map_err(|error| error.to_string())?;
89 Ok(ProductContext::new(product, context.env))
90}
91
92fn load_alias_file(file: &std::path::Path) -> Result<Option<Value>, String> {
93 let text = match std::fs::read_to_string(file) {
94 Ok(text) => text,
95 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
96 Err(error) => {
97 return Err(format!(
98 "cannot read product configuration {}: {error}",
99 file.display()
100 ));
101 }
102 };
103 serde_json::from_str(&text)
104 .map(Some)
105 .map_err(|_| format!("invalid product configuration JSON: {}", file.display()))
106}
107
108fn apply_aliases(descriptor: &mut ProductDescriptor, value: &Value) -> Result<(), String> {
109 let Some(aliases) = value.pointer("/commands/aliases") else {
110 return Ok(());
111 };
112 let aliases = aliases
113 .as_object()
114 .ok_or("commands.aliases must be an object")?;
115 for (id, value) in aliases {
116 let board = descriptor
117 .boards
118 .iter_mut()
119 .find(|board| &board.id == id)
120 .ok_or_else(|| format!("commands.aliases names an excluded board: {id}"))?;
121 let values = value
122 .as_array()
123 .ok_or_else(|| format!("commands.aliases.{id} must be an array"))?;
124 for value in values {
125 let alias = value
126 .as_str()
127 .ok_or_else(|| format!("commands.aliases.{id} must contain strings"))?;
128 board.aliases.push(alias.to_owned());
129 }
130 }
131 Ok(())
132}
133
134pub(crate) fn gui_config_file(cx: &App) -> PathBuf {
135 cx.global::<ProductFiles>().config.clone()
136}
137
138#[cfg(test)]
139mod tests {
140 use super::{
141 ProductFiles, apply_aliases, config_file, context_with_env, load_alias_file,
142 preference_file,
143 };
144 use subspace_product::{OsKind, PlatformEnv, ProductContext, fixture, validate_product};
145
146 #[test]
147 fn product_aliases_validate_collisions_and_excluded_boards() {
148 let mut descriptor = fixture::descriptor();
149 apply_aliases(
150 &mut descriptor,
151 &serde_json::json!({"commands":{"aliases":{"github":["gh"]}}}),
152 )
153 .unwrap();
154 assert!(
155 validate_product(&descriptor)
156 .unwrap()
157 .board_for_command("gh")
158 .is_some()
159 );
160 apply_aliases(
161 &mut descriptor,
162 &serde_json::json!({"commands":{"aliases":{"github":["github"]}}}),
163 )
164 .unwrap();
165 assert!(validate_product(&descriptor).is_err());
166 assert!(
167 apply_aliases(
168 &mut descriptor,
169 &serde_json::json!({"commands":{"aliases":{"missing":["m"]}}})
170 )
171 .unwrap_err()
172 .contains("excluded board")
173 );
174 }
175
176 #[test]
177 fn gui_files_are_product_specific() {
178 let root = tempfile::tempdir().unwrap();
179 let known = fixture::products().unwrap();
180 let env = PlatformEnv {
181 os: OsKind::Macos,
182 home: root.path().to_owned(),
183 xdg_config_home: None,
184 xdg_state_home: None,
185 app_data: None,
186 local_app_data: None,
187 };
188 let context = ProductContext::new(known[0].clone(), env.clone());
189 let files = ProductFiles::for_context(&context);
190 assert_eq!(files.state, preference_file(&context));
191 assert_eq!(files.config, config_file(&context));
192 let name = subspace_product::product_data_name("subspace");
193 assert!(
194 preference_file(&context).ends_with(format!("Application Support/{name}/state.json"))
195 );
196 assert!(config_file(&context).ends_with(format!("Application Support/{name}/config.json")));
197 assert!(!root.path().join("Library").exists());
198 let mut descriptor = fixture::descriptor();
199 let reloaded = context_with_env(&mut descriptor, env).unwrap();
200 assert_eq!(reloaded.product.id.as_str(), "subspace");
201 assert!(!root.path().join("Library").exists());
202 }
203
204 #[test]
205 fn alias_loader_does_not_repeat_configuration_contents() {
206 let root = tempfile::tempdir().unwrap();
207 let file = root.path().join("config.json");
208 assert_eq!(load_alias_file(&file).unwrap(), None);
209 std::fs::write(&file, "a-secret-that-is-not-json").unwrap();
210 let error = load_alias_file(&file).unwrap_err();
211 assert!(error.contains("invalid product configuration JSON"));
212 assert!(!error.contains("a-secret"));
213 std::fs::write(&file, "{}").unwrap();
214 assert_eq!(load_alias_file(&file).unwrap(), Some(serde_json::json!({})));
215 }
216}