1use crate::error::{Result, VirtuosoError};
2use dotenvy::dotenv;
3use std::env;
4use std::path::PathBuf;
5
6#[derive(Debug, Clone)]
7pub struct Config {
8 #[allow(dead_code)]
9 pub profile: Option<String>,
10 pub remote_host: Option<String>,
11 pub remote_user: Option<String>,
12 pub port: u16,
13 pub jump_host: Option<String>,
14 pub jump_user: Option<String>,
15 pub ssh_port: Option<u16>,
16 pub ssh_key: Option<String>,
17 pub timeout: u64,
18 pub keep_remote_files: bool,
19 pub spectre_cmd: String,
20 pub spectre_args: Vec<String>,
21}
22
23impl Config {
24 fn env_with_profile(key: &str, profile: Option<&str>) -> Option<String> {
26 if let Some(p) = profile {
27 if let Ok(v) = env::var(format!("{key}_{p}")) {
28 if !v.is_empty() {
29 return Some(v);
30 }
31 }
32 }
33 env::var(key).ok().filter(|s| !s.is_empty())
34 }
35
36 pub fn from_env() -> Result<Self> {
37 let profile = env::var("VB_PROFILE").ok();
38 Self::from_env_with_profile(profile.as_deref())
39 }
40
41 pub fn from_env_with_profile(profile: Option<&str>) -> Result<Self> {
42 if let Err(e) = dotenv() {
43 if !e.not_found() {
44 tracing::warn!("failed to load .env: {e}");
45 }
46 }
47
48 let remote_host = Self::env_with_profile("VB_REMOTE_HOST", profile);
49
50 let port: u16 = Self::env_with_profile("VB_PORT", profile)
51 .and_then(|v| v.parse().ok())
52 .unwrap_or_else(Self::default_port);
53
54 if port == 0 {
55 return Err(VirtuosoError::Config(
56 "VB_PORT must be between 1 and 65535".into(),
57 ));
58 }
59
60 Ok(Self {
61 profile: profile.map(|s| s.to_string()),
62 remote_host,
63 remote_user: Self::env_with_profile("VB_REMOTE_USER", profile),
64 port,
65 jump_host: Self::env_with_profile("VB_JUMP_HOST", profile),
66 jump_user: Self::env_with_profile("VB_JUMP_USER", profile),
67 ssh_port: Self::env_with_profile("VB_SSH_PORT", profile).and_then(|v| v.parse().ok()),
68 ssh_key: Self::env_with_profile("VB_SSH_KEY", profile),
69 timeout: Self::env_with_profile("VB_TIMEOUT", profile)
70 .and_then(|v| v.parse().ok())
71 .unwrap_or(30),
72 keep_remote_files: Self::env_with_profile("VB_KEEP_REMOTE_FILES", profile)
73 .map(|v| v == "1" || v.to_lowercase() == "true")
74 .unwrap_or(false),
75 spectre_cmd: Self::env_with_profile("VB_SPECTRE_CMD", profile)
76 .unwrap_or_else(|| "spectre".into()),
77 spectre_args: Self::env_with_profile("VB_SPECTRE_ARGS", profile)
78 .map(|v| shlex::split(&v).unwrap_or_default())
79 .unwrap_or_default(),
80 })
81 }
82
83 fn default_port() -> u16 {
86 let user = env::var("USER")
87 .or_else(|_| env::var("USERNAME"))
88 .unwrap_or_default();
89 let hash: u16 = user.bytes().map(|b| b as u16).sum::<u16>() % 500;
90 65000 + hash
91 }
92
93 pub fn is_remote(&self) -> bool {
94 self.remote_host.is_some()
95 }
96
97 #[allow(dead_code)]
98 pub fn ssh_target(&self) -> String {
99 let host = self.remote_host.as_deref().unwrap_or("");
100 match &self.remote_user {
101 Some(user) => format!("{user}@{host}"),
102 None => host.to_string(),
103 }
104 }
105
106 #[allow(dead_code)]
107 pub fn ssh_jump(&self) -> Option<String> {
108 match (&self.jump_host, &self.jump_user) {
109 (Some(host), Some(user)) => Some(format!("{user}@{host}")),
110 (Some(host), None) => Some(host.clone()),
111 _ => None,
112 }
113 }
114}
115
116#[allow(dead_code)]
117pub fn find_project_root() -> Option<PathBuf> {
118 let mut current = std::env::current_dir().ok()?;
119 loop {
120 if current.join(".env").exists() {
121 return Some(current);
122 }
123 if current.join("pyproject.toml").exists() {
124 let content = std::fs::read_to_string(current.join("pyproject.toml")).ok()?;
125 if content.contains("virtuoso-bridge") || content.contains("virtuoso-cli") {
126 return Some(current);
127 }
128 }
129 if !current.pop() {
130 break;
131 }
132 }
133 None
134}