1use std::path::PathBuf;
15
16pub fn home_from_env(get: impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
20 let nonempty = |k: &str| get(k).filter(|v| !v.is_empty());
21 if let Some(h) = nonempty("HOME") {
22 return Some(PathBuf::from(h));
23 }
24 if let Some(up) = nonempty("USERPROFILE") {
25 return Some(PathBuf::from(up));
26 }
27 if let (Some(d), Some(p)) = (nonempty("HOMEDRIVE"), nonempty("HOMEPATH")) {
28 return Some(PathBuf::from(format!("{d}{p}")));
29 }
30 None
31}
32
33pub fn clipboard_candidates(os: &str) -> Vec<(&'static str, Vec<&'static str>)> {
38 match os {
39 "macos" => vec![("pbcopy", vec![])],
40 "windows" => vec![("clip", vec![])],
41 _ => vec![
43 ("wl-copy", vec![]),
44 ("xclip", vec!["-selection", "clipboard"]),
45 ("xsel", vec!["--clipboard", "--input"]),
46 ],
47 }
48}
49
50pub const PROVIDERS: &[&str] = &["github.com", "bitbucket.org", "gitlab.com"];
54
55#[derive(Debug, PartialEq, Eq)]
57pub enum ProviderChoice {
58 Host(String),
61 Custom,
63 Invalid,
65}
66
67pub fn provider_choice(raw: &str) -> ProviderChoice {
72 let t = raw.trim();
73 if t.is_empty() {
74 return ProviderChoice::Host(PROVIDERS[0].to_string());
75 }
76 if let Ok(n) = t.parse::<usize>() {
77 if (1..=PROVIDERS.len()).contains(&n) {
78 return ProviderChoice::Host(PROVIDERS[n - 1].to_string());
79 }
80 if n == PROVIDERS.len() + 1 {
81 return ProviderChoice::Custom;
82 }
83 return ProviderChoice::Invalid;
84 }
85 ProviderChoice::Host(t.to_string())
86}
87
88pub fn host_block(alias: &str, hostname: &str, port: Option<u16>, macos: bool) -> String {
90 let mut s = String::new();
91 s.push_str(&format!("Host {alias}\n"));
92 s.push_str(&format!(" HostName {hostname}\n"));
93 s.push_str(" User git\n");
94 s.push_str(" AddKeysToAgent yes\n");
95 if macos {
96 s.push_str(" UseKeychain yes\n");
97 }
98 s.push_str(" IdentitiesOnly yes\n");
99 s.push_str(&format!(" IdentityFile ~/.ssh/id_{alias}\n"));
100 if let Some(p) = port {
101 s.push_str(&format!(" Port {p}\n"));
102 }
103 s
104}
105
106pub fn upsert_block(existing: &str, alias: &str, block: &str) -> String {
109 let kept = remove_host_block(existing, alias);
110 let mut out = kept.trim_end().to_string();
111 if !out.is_empty() {
112 out.push_str("\n\n");
113 }
114 out.push_str(block.trim_end());
115 out.push('\n');
116 out
117}
118
119fn remove_host_block(content: &str, alias: &str) -> String {
122 let mut out = String::new();
123 let mut skipping = false;
124 for line in content.lines() {
125 if let Some(rest) = line.trim_start().strip_prefix("Host ") {
126 skipping = rest.split_whitespace().next() == Some(alias);
127 }
128 if !skipping {
129 out.push_str(line);
130 out.push('\n');
131 }
132 }
133 out
134}
135
136pub fn ensure_include(ssh_config: &str) -> Option<String> {
139 if ssh_config.lines().any(|l| l.trim() == "Include git_users") {
140 return None;
141 }
142 let mut s = String::from("Include git_users\n");
143 if !ssh_config.trim().is_empty() {
144 s.push('\n');
145 s.push_str(ssh_config);
146 if !ssh_config.ends_with('\n') {
147 s.push('\n');
148 }
149 }
150 Some(s)
151}
152
153pub fn list_hosts(git_users: &str) -> Vec<(String, String)> {
155 let mut hosts: Vec<(String, String)> = Vec::new();
156 for line in git_users.lines() {
157 let t = line.trim_start();
158 if let Some(rest) = t.strip_prefix("Host ") {
159 if let Some(a) = rest.split_whitespace().next() {
160 hosts.push((a.to_string(), String::new()));
161 }
162 } else if let Some(idf) = t.strip_prefix("IdentityFile ") {
163 if let Some(last) = hosts.last_mut() {
164 last.1 = idf.trim().to_string();
165 }
166 }
167 }
168 hosts
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 #[test]
176 fn provider_menu_maps_input() {
177 assert_eq!(
179 provider_choice(""),
180 ProviderChoice::Host("github.com".into())
181 );
182 assert_eq!(
183 provider_choice(" "),
184 ProviderChoice::Host("github.com".into())
185 );
186 assert_eq!(
188 provider_choice("1"),
189 ProviderChoice::Host("github.com".into())
190 );
191 assert_eq!(
192 provider_choice("2"),
193 ProviderChoice::Host("bitbucket.org".into())
194 );
195 assert_eq!(
196 provider_choice("3"),
197 ProviderChoice::Host("gitlab.com".into())
198 );
199 assert_eq!(provider_choice("4"), ProviderChoice::Custom);
201 assert_eq!(provider_choice("9"), ProviderChoice::Invalid);
203 assert_eq!(provider_choice("0"), ProviderChoice::Invalid);
204 assert_eq!(
206 provider_choice("git.mycorp.com"),
207 ProviderChoice::Host("git.mycorp.com".into())
208 );
209 }
210
211 #[test]
212 fn block_is_os_aware() {
213 let mac = host_block("acme", "github.com", None, true);
214 assert!(mac.contains("Host acme"));
215 assert!(mac.contains("IdentityFile ~/.ssh/id_acme"));
216 assert!(mac.contains("UseKeychain yes"));
217 let linux = host_block("acme", "github.com", None, false);
218 assert!(!linux.contains("UseKeychain"));
219 }
220
221 #[test]
222 fn block_includes_port_when_set() {
223 assert!(host_block("a", "h", Some(2222), false).contains("Port 2222"));
224 assert!(!host_block("a", "h", None, false).contains("Port"));
225 }
226
227 #[test]
228 fn upsert_replaces_existing_alias_keeps_others() {
229 let existing = "Include project_config\n\nHost acme\n HostName old\n IdentityFile ~/.ssh/id_acme\n\nHost other\n HostName github.com\n";
230 let new_block = host_block("acme", "github.com", None, true);
231 let out = upsert_block(existing, "acme", &new_block);
232 assert_eq!(
233 out.matches("Host acme").count(),
234 1,
235 "exactly one acme block:\n{out}"
236 );
237 assert!(out.contains("HostName github.com")); assert!(!out.contains("HostName old")); assert!(out.contains("Host other")); assert!(out.contains("Include project_config")); }
242
243 #[test]
244 fn ensure_include_adds_only_when_missing() {
245 assert!(ensure_include("Host x\n")
246 .unwrap()
247 .starts_with("Include git_users"));
248 assert_eq!(ensure_include("Include git_users\nHost x\n"), None);
249 }
250
251 fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
252 let m: std::collections::HashMap<String, String> = pairs
253 .iter()
254 .map(|(k, v)| (k.to_string(), v.to_string()))
255 .collect();
256 move |k: &str| m.get(k).cloned()
257 }
258
259 #[test]
260 fn home_resolves_home_then_userprofile_then_homedrive() {
261 assert_eq!(
263 home_from_env(env_of(&[
264 ("HOME", "/home/u"),
265 ("USERPROFILE", "C:\\Users\\u")
266 ])),
267 Some(PathBuf::from("/home/u"))
268 );
269 assert_eq!(
271 home_from_env(env_of(&[("USERPROFILE", "C:\\Users\\u")])),
272 Some(PathBuf::from("C:\\Users\\u"))
273 );
274 assert_eq!(
276 home_from_env(env_of(&[("HOME", ""), ("USERPROFILE", "C:\\Users\\u")])),
277 Some(PathBuf::from("C:\\Users\\u"))
278 );
279 assert_eq!(
281 home_from_env(env_of(&[("HOMEDRIVE", "C:"), ("HOMEPATH", "\\Users\\u")])),
282 Some(PathBuf::from("C:\\Users\\u"))
283 );
284 assert_eq!(home_from_env(env_of(&[])), None);
286 }
287
288 #[test]
289 fn clipboard_candidates_are_os_specific() {
290 let names = |os| {
291 clipboard_candidates(os)
292 .into_iter()
293 .map(|(p, _)| p)
294 .collect::<Vec<_>>()
295 };
296 assert_eq!(names("macos"), vec!["pbcopy"]);
297 assert_eq!(names("windows"), vec!["clip"]);
298 assert_eq!(names("linux"), vec!["wl-copy", "xclip", "xsel"]);
299 }
300
301 #[test]
302 fn lists_hosts_with_identity() {
303 let g =
304 "Host acme\n IdentityFile ~/.ssh/id_acme\nHost work\n IdentityFile ~/.ssh/id_work\n";
305 assert_eq!(
306 list_hosts(g),
307 vec![
308 ("acme".into(), "~/.ssh/id_acme".into()),
309 ("work".into(), "~/.ssh/id_work".into())
310 ]
311 );
312 }
313}