ai_usagebar/modelstudio/
mod.rs1pub mod creds;
13pub mod fetch;
14pub mod types;
15pub mod vendor;
16
17use std::path::{Path, PathBuf};
18
19use crate::config::ModelStudioConfig;
20use crate::error::Result;
21
22pub const APP_DIR_NAME: &str = ".bailian";
24pub const CONFIG_FILE_NAME: &str = "config.json";
26pub const CONFIG_DIR_ENV: &str = "BAILIAN_CONFIG_DIR";
28
29pub fn config_path_in(cfg: &ModelStudioConfig, env_dir: Option<PathBuf>, home: &Path) -> PathBuf {
34 cfg.config_dir
35 .clone()
36 .or(env_dir)
37 .unwrap_or_else(|| home.join(APP_DIR_NAME))
38 .join(CONFIG_FILE_NAME)
39}
40
41pub fn config_path(cfg: &ModelStudioConfig) -> Result<PathBuf> {
43 let env_dir = std::env::var_os(CONFIG_DIR_ENV)
44 .filter(|value| !value.is_empty())
45 .map(PathBuf::from)
46 .map(|p| expand_tilde(&p));
47 Ok(config_path_in(cfg, env_dir, &crate::cache::home_dir()?))
48}
49
50fn expand_tilde(p: &Path) -> PathBuf {
54 let home = crate::cache::home_dir().unwrap_or_else(|_| p.to_path_buf());
55 expand_tilde_in(p, &home)
56}
57
58fn expand_tilde_in(p: &Path, home: &Path) -> PathBuf {
60 let Some(s) = p.to_str() else {
61 return p.to_path_buf();
62 };
63 let rest = if s == "~" {
64 ""
65 } else if let Some(r) = s.strip_prefix("~/") {
66 r
67 } else {
68 return p.to_path_buf();
69 };
70 if rest.is_empty() {
71 home.to_path_buf()
72 } else {
73 home.join(rest)
74 }
75}
76
77pub fn resolve_credentials(cfg: &ModelStudioConfig) -> Result<creds::Credentials> {
79 creds::read_from(&config_path(cfg)?)
80}
81
82pub use fetch::{FetchOutcome, fetch_snapshot_with};
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
89 fn the_default_path_lives_in_the_bl_cli_dir() {
90 let cfg = ModelStudioConfig::default();
91 let path = config_path_in(&cfg, None, Path::new("/home/u"));
92 assert_eq!(path, PathBuf::from("/home/u/.bailian/config.json"));
93 }
94
95 #[test]
96 fn a_configured_dir_wins_over_the_env_and_the_default() {
97 let cfg = ModelStudioConfig {
98 config_dir: Some(PathBuf::from("/cfg/bl")),
99 ..ModelStudioConfig::default()
100 };
101 let path = config_path_in(&cfg, Some(PathBuf::from("/env/bl")), Path::new("/home/u"));
102 assert_eq!(path, PathBuf::from("/cfg/bl/config.json"));
103 }
104
105 #[test]
106 fn the_env_dir_wins_over_the_default() {
107 let cfg = ModelStudioConfig::default();
108 let path = config_path_in(&cfg, Some(PathBuf::from("/env/bl")), Path::new("/home/u"));
109 assert_eq!(path, PathBuf::from("/env/bl/config.json"));
110 }
111
112 #[test]
113 fn a_tilde_in_the_env_dir_expands() {
114 assert_eq!(
115 expand_tilde_in(Path::new("~/bl"), Path::new("/home/u")),
116 PathBuf::from("/home/u/bl")
117 );
118 assert_eq!(
120 expand_tilde_in(Path::new("~"), Path::new("/home/u")),
121 PathBuf::from("/home/u")
122 );
123 assert_eq!(
124 expand_tilde_in(Path::new("~other/config"), Path::new("/home/u")),
125 PathBuf::from("~other/config")
126 );
127 }
128}