systemprompt_cli/shared/
profile.rs1use std::path::{Path, PathBuf};
2
3use anyhow::{Context, Result};
4use rand::distr::Alphanumeric;
5use rand::{rng, Rng};
6use systemprompt_cloud::{ProfilePath, ProjectContext};
7use systemprompt_loader::ProfileLoader;
8use systemprompt_models::Profile;
9
10#[derive(Debug, thiserror::Error)]
11pub enum ProfileResolutionError {
12 #[error(
13 "No profiles found.\n\nCreate a profile with: systemprompt cloud profile create <name>"
14 )]
15 NoProfilesFound,
16
17 #[error(
18 "Profile '{0}' not found.\n\nRun 'systemprompt cloud profile list' to see available \
19 profiles."
20 )]
21 ProfileNotFound(String),
22
23 #[error("Profile discovery failed: {0}")]
24 DiscoveryFailed(#[from] anyhow::Error),
25
26 #[error(
27 "Multiple profiles found: {profiles:?}\n\nUse --profile <name> or 'systemprompt admin \
28 session switch <profile>'"
29 )]
30 MultipleProfilesFound { profiles: Vec<String> },
31}
32
33pub fn resolve_profile_path(
34 cli_override: Option<&str>,
35 from_session: Option<PathBuf>,
36) -> Result<PathBuf, ProfileResolutionError> {
37 if let Some(profile_input) = cli_override {
38 return resolve_profile_input(profile_input);
39 }
40
41 if let Ok(path_str) = std::env::var("SYSTEMPROMPT_PROFILE") {
42 return resolve_profile_input(&path_str);
43 }
44
45 if let Some(path) = from_session.filter(|p| p.exists()) {
46 return Ok(path);
47 }
48
49 let mut profiles = discover_profiles()?;
50 match profiles.len() {
51 0 => Err(ProfileResolutionError::NoProfilesFound),
52 1 => Ok(profiles.swap_remove(0).path),
53 _ => Err(ProfileResolutionError::MultipleProfilesFound {
54 profiles: profiles.iter().map(|p| p.name.clone()).collect(),
55 }),
56 }
57}
58
59pub fn is_path_input(input: &str) -> bool {
60 let path = Path::new(input);
61 let has_yaml_extension = path
62 .extension()
63 .is_some_and(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"));
64
65 input.contains(std::path::MAIN_SEPARATOR)
66 || input.contains('/')
67 || has_yaml_extension
68 || input.starts_with('.')
69 || input.starts_with('~')
70}
71
72fn resolve_profile_input(input: &str) -> Result<PathBuf, ProfileResolutionError> {
73 if is_path_input(input) {
74 return resolve_profile_from_path(input);
75 }
76 resolve_profile_by_name(input)?
77 .ok_or_else(|| ProfileResolutionError::ProfileNotFound(input.to_string()))
78}
79
80pub fn resolve_profile_from_path(path_str: &str) -> Result<PathBuf, ProfileResolutionError> {
81 let path = expand_path(path_str);
82
83 if path.exists() {
84 return Ok(path);
85 }
86
87 let profile_yaml = path.join("profile.yaml");
88 if profile_yaml.exists() {
89 return Ok(profile_yaml);
90 }
91
92 Err(ProfileResolutionError::ProfileNotFound(
93 path_str.to_string(),
94 ))
95}
96
97fn expand_path(path_str: &str) -> PathBuf {
98 if path_str.starts_with('~') {
99 if let Some(home) = dirs::home_dir() {
100 return home.join(
101 path_str
102 .strip_prefix("~/")
103 .unwrap_or_else(|| &path_str[1..]),
104 );
105 }
106 }
107 PathBuf::from(path_str)
108}
109
110pub fn resolve_profile_with_data(
111 profile_input: &str,
112) -> Result<(PathBuf, Profile), ProfileResolutionError> {
113 let path = resolve_profile_input(profile_input)?;
114 let profile =
115 ProfileLoader::load_from_path(&path).map_err(ProfileResolutionError::DiscoveryFailed)?;
116 Ok((path, profile))
117}
118
119fn resolve_profile_by_name(name: &str) -> Result<Option<PathBuf>, ProfileResolutionError> {
120 let ctx = ProjectContext::discover();
121 let profiles_dir = ctx.profiles_dir();
122 let target_dir = profiles_dir.join(name);
123 let config_path = ProfilePath::Config.resolve(&target_dir);
124
125 if config_path.exists() {
126 return Ok(Some(config_path));
127 }
128
129 let profiles = discover_profiles()?;
130 Ok(profiles
131 .into_iter()
132 .find(|p| p.name == name)
133 .map(|p| p.path))
134}
135
136#[derive(Debug)]
137pub struct DiscoveredProfile {
138 pub name: String,
139 pub path: PathBuf,
140 pub profile: Profile,
141}
142
143pub fn discover_profiles() -> Result<Vec<DiscoveredProfile>> {
144 let ctx = ProjectContext::discover();
145 let profiles_dir = ctx.profiles_dir();
146
147 if !profiles_dir.exists() {
148 return Ok(Vec::new());
149 }
150
151 let entries = std::fs::read_dir(&profiles_dir).with_context(|| {
152 format!(
153 "Failed to read profiles directory: {}",
154 profiles_dir.display()
155 )
156 })?;
157
158 let profiles = entries
159 .filter_map(std::result::Result::ok)
160 .filter(|e| e.path().is_dir())
161 .filter_map(|e| build_discovered_profile(&e))
162 .collect();
163
164 Ok(profiles)
165}
166
167fn build_discovered_profile(entry: &std::fs::DirEntry) -> Option<DiscoveredProfile> {
168 let profile_yaml = ProfilePath::Config.resolve(&entry.path());
169 if !profile_yaml.exists() {
170 return None;
171 }
172
173 let name = entry.file_name().to_string_lossy().to_string();
174 let profile = ProfileLoader::load_from_path(&profile_yaml).ok()?;
175
176 Some(DiscoveredProfile {
177 name,
178 path: profile_yaml,
179 profile,
180 })
181}
182
183pub fn generate_display_name(name: &str) -> String {
184 match name.to_lowercase().as_str() {
185 "dev" | "development" => "Development".to_string(),
186 "prod" | "production" => "Production".to_string(),
187 "staging" | "stage" => "Staging".to_string(),
188 "test" | "testing" => "Test".to_string(),
189 "local" => "Local Development".to_string(),
190 "cloud" => "Cloud".to_string(),
191 _ => capitalize_first(name),
192 }
193}
194
195fn capitalize_first(name: &str) -> String {
196 let mut chars = name.chars();
197 chars.next().map_or_else(String::new, |first| {
198 first.to_uppercase().chain(chars).collect()
199 })
200}
201
202pub fn generate_jwt_secret() -> String {
203 let mut rng = rng();
204 (0..64)
205 .map(|_| rng.sample(Alphanumeric))
206 .map(char::from)
207 .collect()
208}
209
210pub fn save_profile_yaml(profile: &Profile, path: &Path, header: Option<&str>) -> Result<()> {
211 if let Some(parent) = path.parent() {
212 std::fs::create_dir_all(parent)
213 .with_context(|| format!("Failed to create directory {}", parent.display()))?;
214 }
215
216 let yaml = serde_yaml::to_string(profile).context("Failed to serialize profile")?;
217
218 let content = header.map_or_else(|| yaml.clone(), |h| format!("{}\n\n{}", h, yaml));
219
220 std::fs::write(path, content).with_context(|| format!("Failed to write {}", path.display()))?;
221
222 Ok(())
223}