1use std::cell::RefCell;
2use std::collections::BTreeMap;
3#[cfg(not(windows))]
4use std::collections::BTreeSet;
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7
8use crate::value::{VmError, VmValue};
9
10thread_local! {
11 static SELECTED_DEFAULT_SHELL_ID: RefCell<Option<String>> = const { RefCell::new(None) };
12}
13
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct ShellDescriptor {
16 pub id: String,
17 pub label: String,
18 pub path: String,
19 pub platform: String,
20 pub available: bool,
21 pub supports_login: bool,
22 pub supports_interactive: bool,
23 pub default_args: Vec<String>,
24 pub login_args: Vec<String>,
25 pub source: String,
26}
27
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct ShellCatalog {
30 pub shells: Vec<ShellDescriptor>,
31 pub default_shell_id: Option<String>,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct ShellInvocation {
36 pub program: String,
37 pub args: Vec<String>,
38 pub command_arg_index: usize,
39 pub shell: ShellDescriptor,
40}
41
42pub fn clear_selected_default_shell_for_test() {
43 SELECTED_DEFAULT_SHELL_ID.with(|selected| *selected.borrow_mut() = None);
44}
45
46pub fn discover_shells() -> ShellCatalog {
47 let shells = platform_shells();
48 let selected = SELECTED_DEFAULT_SHELL_ID.with(|selected| selected.borrow().clone());
49 let default_shell_id = selected
50 .filter(|id| {
51 shells
52 .iter()
53 .any(|shell| shell.id == *id && shell.available)
54 })
55 .or_else(|| {
56 shells
57 .iter()
58 .find(|shell| shell.available)
59 .map(|shell| shell.id.clone())
60 })
61 .or_else(|| shells.first().map(|shell| shell.id.clone()));
62 ShellCatalog {
63 shells,
64 default_shell_id,
65 }
66}
67
68pub fn get_default_shell() -> Option<ShellDescriptor> {
69 let catalog = discover_shells();
70 catalog
71 .default_shell_id
72 .as_deref()
73 .and_then(|id| catalog.shells.iter().find(|shell| shell.id == id))
74 .cloned()
75 .or_else(|| catalog.shells.first().cloned())
76}
77
78pub fn set_default_shell(shell_id: &str) -> Result<ShellDescriptor, String> {
79 let catalog = discover_shells();
80 let Some(shell) = catalog
81 .shells
82 .iter()
83 .find(|shell| shell.id == shell_id && shell.available)
84 .cloned()
85 else {
86 return Err(format!("unknown or unavailable shell id {shell_id:?}"));
87 };
88 SELECTED_DEFAULT_SHELL_ID.with(|selected| *selected.borrow_mut() = Some(shell.id.clone()));
89 Ok(shell)
90}
91
92pub fn list_shells_vm_value() -> VmValue {
93 shell_catalog_to_vm_value(&discover_shells())
94}
95
96pub fn default_shell_vm_value() -> VmValue {
97 get_default_shell()
98 .map(|shell| shell_descriptor_to_vm_value(&shell))
99 .unwrap_or(VmValue::Nil)
100}
101
102pub fn set_default_shell_vm_value(params: &BTreeMap<String, VmValue>) -> Result<VmValue, VmError> {
103 let shell_id = params
104 .get("shell_id")
105 .or_else(|| params.get("id"))
106 .and_then(vm_string)
107 .ok_or_else(|| {
108 VmError::Runtime("process.set_default_shell missing shell_id".to_string())
109 })?;
110 set_default_shell(shell_id)
111 .map(|shell| shell_descriptor_to_vm_value(&shell))
112 .map_err(|err| VmError::Runtime(format!("process.set_default_shell: {err}")))
113}
114
115pub fn shell_invocation_vm_value(params: &BTreeMap<String, VmValue>) -> Result<VmValue, VmError> {
116 resolve_invocation_from_vm_params(params)
117 .map(|invocation| shell_invocation_to_vm_value(&invocation))
118 .map_err(|err| VmError::Runtime(format!("process.shell_invocation: {err}")))
119}
120
121pub fn default_shell_invocation(command: &str) -> Result<ShellInvocation, String> {
122 let shell = get_default_shell().ok_or_else(|| "no shell candidates available".to_string())?;
123 Ok(invocation_for_shell(
124 shell,
125 command.to_string(),
126 false,
127 false,
128 ))
129}
130
131pub fn resolve_invocation_from_vm_params(
132 params: &BTreeMap<String, VmValue>,
133) -> Result<ShellInvocation, String> {
134 let command = params
135 .get("command")
136 .and_then(vm_string)
137 .unwrap_or("{command}")
138 .to_string();
139 let login = optional_bool(params, "login").unwrap_or(false);
140 let interactive = optional_bool(params, "interactive").unwrap_or(false);
141 let shell = resolve_shell_from_vm_params(params)?;
142 Ok(invocation_for_shell(shell, command, login, interactive))
143}
144
145pub fn resolve_shell_from_vm_params(
146 params: &BTreeMap<String, VmValue>,
147) -> Result<ShellDescriptor, String> {
148 if let Some(value) = params.get("shell") {
149 if let Some(shell) = value.as_dict() {
150 return shell_descriptor_from_vm_dict(shell);
151 }
152 if !matches!(value, VmValue::Nil) {
153 return Err(format!("shell must be a dict, got {}", value.type_name()));
154 }
155 }
156 if let Some(value) = params.get("shell_id") {
157 if let Some(shell_id) = vm_string(value) {
158 return shell_by_id(shell_id);
159 }
160 if !matches!(value, VmValue::Nil) {
161 return Err(format!(
162 "shell_id must be a string, got {}",
163 value.type_name()
164 ));
165 }
166 }
167 get_default_shell().ok_or_else(|| "no default shell available".to_string())
168}
169
170pub fn shell_descriptor_to_vm_value(shell: &ShellDescriptor) -> VmValue {
171 let mut map = BTreeMap::new();
172 map.insert("id".to_string(), string(&shell.id));
173 map.insert("label".to_string(), string(&shell.label));
174 map.insert("path".to_string(), string(&shell.path));
175 map.insert("platform".to_string(), string(&shell.platform));
176 map.insert("available".to_string(), VmValue::Bool(shell.available));
177 map.insert(
178 "supports_login".to_string(),
179 VmValue::Bool(shell.supports_login),
180 );
181 map.insert(
182 "supports_interactive".to_string(),
183 VmValue::Bool(shell.supports_interactive),
184 );
185 map.insert("default_args".to_string(), string_list(&shell.default_args));
186 map.insert("login_args".to_string(), string_list(&shell.login_args));
187 map.insert("source".to_string(), string(&shell.source));
188 VmValue::Dict(Rc::new(map))
189}
190
191pub fn shell_invocation_to_vm_value(invocation: &ShellInvocation) -> VmValue {
192 let mut map = BTreeMap::new();
193 map.insert("program".to_string(), string(&invocation.program));
194 map.insert("args".to_string(), string_list(&invocation.args));
195 map.insert(
196 "command_arg_index".to_string(),
197 VmValue::Int(invocation.command_arg_index as i64),
198 );
199 map.insert(
200 "shell".to_string(),
201 shell_descriptor_to_vm_value(&invocation.shell),
202 );
203 VmValue::Dict(Rc::new(map))
204}
205
206fn shell_catalog_to_vm_value(catalog: &ShellCatalog) -> VmValue {
207 let mut map = BTreeMap::new();
208 map.insert(
209 "shells".to_string(),
210 VmValue::List(Rc::new(
211 catalog
212 .shells
213 .iter()
214 .map(shell_descriptor_to_vm_value)
215 .collect(),
216 )),
217 );
218 map.insert(
219 "default_shell_id".to_string(),
220 catalog
221 .default_shell_id
222 .as_ref()
223 .map(|id| string(id))
224 .unwrap_or(VmValue::Nil),
225 );
226 VmValue::Dict(Rc::new(map))
227}
228
229fn shell_descriptor_from_vm_dict(
230 dict: &BTreeMap<String, VmValue>,
231) -> Result<ShellDescriptor, String> {
232 if let Some(path) = dict.get("path").and_then(vm_string) {
233 let id = dict
234 .get("id")
235 .and_then(vm_string)
236 .map(ToString::to_string)
237 .unwrap_or_else(|| shell_id_from_path(path));
238 let platform = dict
239 .get("platform")
240 .and_then(vm_string)
241 .unwrap_or(platform_name())
242 .to_string();
243 let label = dict
244 .get("label")
245 .and_then(vm_string)
246 .map(ToString::to_string)
247 .unwrap_or_else(|| id.clone());
248 let default_args = dict
249 .get("default_args")
250 .and_then(vm_string_list)
251 .unwrap_or_else(|| default_args_for_id(&id));
252 let login_args = dict
253 .get("login_args")
254 .and_then(vm_string_list)
255 .unwrap_or_else(|| login_args_for_id(&id));
256 let available = dict
257 .get("available")
258 .and_then(|value| match value {
259 VmValue::Bool(value) => Some(*value),
260 _ => None,
261 })
262 .unwrap_or_else(|| executable_available(path));
263 let supports_login = dict
264 .get("supports_login")
265 .and_then(|value| match value {
266 VmValue::Bool(value) => Some(*value),
267 _ => None,
268 })
269 .unwrap_or_else(|| supports_login_for_id(&id));
270 let supports_interactive = dict
271 .get("supports_interactive")
272 .and_then(|value| match value {
273 VmValue::Bool(value) => Some(*value),
274 _ => None,
275 })
276 .unwrap_or_else(|| supports_interactive_for_id(&id));
277 return Ok(ShellDescriptor {
278 id,
279 label,
280 path: path.to_string(),
281 platform,
282 available,
283 supports_login,
284 supports_interactive,
285 default_args,
286 login_args,
287 source: dict
288 .get("source")
289 .and_then(vm_string)
290 .unwrap_or("host")
291 .to_string(),
292 });
293 }
294 if let Some(id) = dict.get("id").and_then(vm_string) {
295 return shell_by_id(id);
296 }
297 Err("shell object requires `path` or `id`".to_string())
298}
299
300fn shell_by_id(shell_id: &str) -> Result<ShellDescriptor, String> {
301 discover_shells()
302 .shells
303 .into_iter()
304 .find(|shell| shell.id == shell_id)
305 .ok_or_else(|| format!("unknown shell id {shell_id:?}"))
306}
307
308fn invocation_for_shell(
309 shell: ShellDescriptor,
310 command: String,
311 login: bool,
312 interactive: bool,
313) -> ShellInvocation {
314 let mut args = if login && shell.supports_login && !shell.login_args.is_empty() {
315 shell.login_args.clone()
316 } else {
317 shell.default_args.clone()
318 };
319 if interactive && shell.supports_interactive && !args.iter().any(|arg| arg == "-i") {
320 args.insert(0, "-i".to_string());
321 }
322 let command_arg_index = args.len();
323 args.push(command);
324 ShellInvocation {
325 program: shell.path.clone(),
326 args,
327 command_arg_index,
328 shell,
329 }
330}
331
332#[cfg(windows)]
333fn platform_shells() -> Vec<ShellDescriptor> {
334 let mut shells = Vec::new();
335 if let Ok(value) = std::env::var("HARN_DEFAULT_SHELL") {
336 push_shell(&mut shells, descriptor_for_path(&value, "configured"));
337 }
338 if let Ok(value) = std::env::var("COMSPEC") {
339 push_shell(&mut shells, descriptor_for_path(&value, "env"));
340 }
341 for (id, label, executable) in [
342 ("pwsh", "PowerShell 7", "pwsh.exe"),
343 ("powershell", "Windows PowerShell", "powershell.exe"),
344 ("cmd", "cmd", "cmd.exe"),
345 ] {
346 let path = find_on_path(executable).unwrap_or_else(|| executable.to_string());
347 let mut shell = descriptor_for_path(&path, "fallback");
348 shell.id = id.to_string();
349 shell.label = label.to_string();
350 push_shell(&mut shells, shell);
351 }
352 shells
353}
354
355#[cfg(not(windows))]
356fn platform_shells() -> Vec<ShellDescriptor> {
357 let mut shells = Vec::new();
358 if let Ok(value) = std::env::var("HARN_DEFAULT_SHELL") {
359 push_shell(&mut shells, descriptor_for_path(&value, "configured"));
360 }
361 if let Ok(value) = std::env::var("SHELL") {
362 push_shell(&mut shells, descriptor_for_path(&value, "env"));
363 }
364 if let Some(value) = login_shell_from_passwd() {
365 push_shell(&mut shells, descriptor_for_path(&value, "login"));
366 }
367 for value in shells_from_etc_shells() {
368 push_shell(&mut shells, descriptor_for_path(&value, "etc_shells"));
369 }
370 for value in [
371 "/bin/zsh",
372 "/bin/bash",
373 "/bin/sh",
374 "/usr/bin/zsh",
375 "/usr/bin/bash",
376 "/usr/bin/sh",
377 ] {
378 push_shell(&mut shells, descriptor_for_path(value, "fallback"));
379 }
380 shells
381}
382
383fn push_shell(shells: &mut Vec<ShellDescriptor>, shell: ShellDescriptor) {
384 if shells.iter().any(|existing| existing.id == shell.id) {
385 return;
386 }
387 shells.push(shell);
388}
389
390fn descriptor_for_path(path: &str, source: &str) -> ShellDescriptor {
391 let id = shell_id_from_path(path);
392 ShellDescriptor {
393 id: id.clone(),
394 label: label_for_id(&id),
395 path: path.to_string(),
396 platform: platform_name().to_string(),
397 available: executable_available(path),
398 supports_login: supports_login_for_id(&id),
399 supports_interactive: supports_interactive_for_id(&id),
400 default_args: default_args_for_id(&id),
401 login_args: login_args_for_id(&id),
402 source: source.to_string(),
403 }
404}
405
406fn shell_id_from_path(path: &str) -> String {
407 let raw = Path::new(path)
408 .file_name()
409 .and_then(|value| value.to_str())
410 .unwrap_or(path)
411 .to_ascii_lowercase();
412 let file_name = raw.strip_suffix(".exe").unwrap_or(&raw);
413 match file_name {
414 "powershell" | "windowspowershell" => "powershell".to_string(),
415 "pwsh" => "pwsh".to_string(),
416 "cmd" => "cmd".to_string(),
417 "bash" => "bash".to_string(),
418 "zsh" => "zsh".to_string(),
419 "fish" => "fish".to_string(),
420 _ if file_name.is_empty() => "shell".to_string(),
421 _ => file_name.to_string(),
422 }
423}
424
425fn label_for_id(id: &str) -> String {
426 match id {
427 "pwsh" => "PowerShell 7",
428 "powershell" => "Windows PowerShell",
429 "cmd" => "cmd",
430 "bash" => "bash",
431 "zsh" => "zsh",
432 "fish" => "fish",
433 "sh" => "sh",
434 other => other,
435 }
436 .to_string()
437}
438
439fn default_args_for_id(id: &str) -> Vec<String> {
440 match id {
441 "cmd" => vec!["/C".to_string()],
442 "pwsh" | "powershell" => vec!["-NoProfile".to_string(), "-Command".to_string()],
443 _ => vec!["-c".to_string()],
444 }
445}
446
447fn login_args_for_id(id: &str) -> Vec<String> {
448 match id {
449 "cmd" | "pwsh" | "powershell" => default_args_for_id(id),
450 _ => vec!["-l".to_string(), "-c".to_string()],
451 }
452}
453
454fn supports_login_for_id(id: &str) -> bool {
455 !matches!(id, "cmd" | "pwsh" | "powershell")
456}
457
458fn supports_interactive_for_id(id: &str) -> bool {
459 !matches!(id, "cmd" | "pwsh" | "powershell")
460}
461
462fn platform_name() -> &'static str {
463 if cfg!(target_os = "macos") {
464 "darwin"
465 } else if cfg!(target_os = "windows") {
466 "windows"
467 } else if cfg!(target_os = "linux") {
468 "linux"
469 } else {
470 std::env::consts::OS
471 }
472}
473
474fn executable_available(path: &str) -> bool {
475 let path_obj = Path::new(path);
476 if path_obj.components().count() > 1 || path_obj.is_absolute() {
477 return path_obj.is_file();
478 }
479 find_on_path(path).is_some()
480}
481
482fn find_on_path(program: &str) -> Option<String> {
483 let path = std::env::var_os("PATH")?;
484 let candidates = path_candidates(program);
485 for dir in std::env::split_paths(&path) {
486 for candidate in &candidates {
487 let full = dir.join(candidate);
488 if full.is_file() {
489 return Some(full.display().to_string());
490 }
491 }
492 }
493 None
494}
495
496#[cfg(windows)]
497fn path_candidates(program: &str) -> Vec<PathBuf> {
498 let mut candidates = vec![PathBuf::from(program)];
499 if Path::new(program).extension().is_none() {
500 for ext in [".exe", ".cmd", ".bat"] {
501 candidates.push(PathBuf::from(format!("{program}{ext}")));
502 }
503 }
504 candidates
505}
506
507#[cfg(not(windows))]
508fn path_candidates(program: &str) -> Vec<PathBuf> {
509 vec![PathBuf::from(program)]
510}
511
512#[cfg(not(windows))]
513fn login_shell_from_passwd() -> Option<String> {
514 let username = std::env::var("USER")
515 .or_else(|_| std::env::var("LOGNAME"))
516 .ok()?;
517 let passwd = std::fs::read_to_string("/etc/passwd").ok()?;
518 passwd.lines().find_map(|line| {
519 let mut parts = line.split(':');
520 let name = parts.next()?;
521 if name != username {
522 return None;
523 }
524 parts
525 .nth(5)
526 .map(str::trim)
527 .filter(|shell| {
528 !shell.is_empty() && !shell.ends_with("/false") && !shell.ends_with("/nologin")
529 })
530 .map(ToString::to_string)
531 })
532}
533
534#[cfg(not(windows))]
535fn shells_from_etc_shells() -> Vec<String> {
536 let Ok(content) = std::fs::read_to_string("/etc/shells") else {
537 return Vec::new();
538 };
539 let mut seen = BTreeSet::new();
540 content
541 .lines()
542 .map(str::trim)
543 .filter(|line| !line.is_empty() && !line.starts_with('#') && line.starts_with('/'))
544 .filter(|line| seen.insert((*line).to_string()))
545 .map(ToString::to_string)
546 .collect()
547}
548
549fn optional_bool(params: &BTreeMap<String, VmValue>, key: &str) -> Option<bool> {
550 match params.get(key) {
551 Some(VmValue::Bool(value)) => Some(*value),
552 _ => None,
553 }
554}
555
556fn vm_string(value: &VmValue) -> Option<&str> {
557 match value {
558 VmValue::String(value) => Some(value.as_ref()),
559 _ => None,
560 }
561}
562
563fn vm_string_list(value: &VmValue) -> Option<Vec<String>> {
564 let VmValue::List(values) = value else {
565 return None;
566 };
567 values
568 .iter()
569 .map(|value| vm_string(value).map(ToString::to_string))
570 .collect()
571}
572
573fn string(value: &str) -> VmValue {
574 VmValue::String(Rc::from(value.to_string()))
575}
576
577fn string_list(values: &[String]) -> VmValue {
578 VmValue::List(Rc::new(values.iter().map(|value| string(value)).collect()))
579}
580
581#[cfg(test)]
582mod tests {
583 use super::*;
584
585 #[test]
586 fn unix_shell_descriptor_uses_split_login_args() {
587 let shell = descriptor_for_path("/bin/zsh", "fallback");
588 assert_eq!(shell.id, "zsh");
589 assert_eq!(shell.default_args, vec!["-c"]);
590 assert_eq!(shell.login_args, vec!["-l", "-c"]);
591 assert!(shell.supports_login);
592 assert!(shell.supports_interactive);
593 }
594
595 #[test]
596 fn windows_shell_descriptor_distinguishes_cmd_and_pwsh() {
597 let cmd = descriptor_for_path("cmd.exe", "fallback");
598 assert_eq!(cmd.id, "cmd");
599 assert_eq!(cmd.default_args, vec!["/C"]);
600 assert!(!cmd.supports_login);
601
602 let pwsh = descriptor_for_path("pwsh.exe", "fallback");
603 assert_eq!(pwsh.id, "pwsh");
604 assert_eq!(pwsh.default_args, vec!["-NoProfile", "-Command"]);
605 }
606
607 #[test]
608 fn invocation_appends_command_after_shell_args() {
609 let shell = ShellDescriptor {
610 id: "zsh".to_string(),
611 label: "zsh".to_string(),
612 path: "/bin/zsh".to_string(),
613 platform: "darwin".to_string(),
614 available: true,
615 supports_login: true,
616 supports_interactive: true,
617 default_args: vec!["-c".to_string()],
618 login_args: vec!["-l".to_string(), "-c".to_string()],
619 source: "test".to_string(),
620 };
621 let invocation = invocation_for_shell(shell, "echo ok".to_string(), true, true);
622 assert_eq!(invocation.program, "/bin/zsh");
623 assert_eq!(invocation.args, vec!["-i", "-l", "-c", "echo ok"]);
624 assert_eq!(invocation.command_arg_index, 3);
625 }
626
627 #[test]
628 fn invocation_without_explicit_shell_uses_default_shell() {
629 clear_selected_default_shell_for_test();
630 let default_shell = get_default_shell().expect("test host should expose a default shell");
631
632 let mut params = BTreeMap::new();
633 params.insert("command".to_string(), string("echo default-shell"));
634
635 let invocation = resolve_invocation_from_vm_params(¶ms).unwrap();
636 assert_eq!(invocation.shell, default_shell);
637 assert_eq!(invocation.program, default_shell.path);
638 assert_eq!(
639 invocation.args[invocation.command_arg_index],
640 "echo default-shell"
641 );
642 }
643
644 #[test]
645 fn malformed_explicit_shell_fields_do_not_fall_back_to_default() {
646 let mut params = BTreeMap::new();
647 params.insert("shell".to_string(), VmValue::Int(1));
648 assert_eq!(
649 resolve_shell_from_vm_params(¶ms).unwrap_err(),
650 "shell must be a dict, got int"
651 );
652
653 let mut params = BTreeMap::new();
654 params.insert("shell_id".to_string(), VmValue::Int(1));
655 assert_eq!(
656 resolve_shell_from_vm_params(¶ms).unwrap_err(),
657 "shell_id must be a string, got int"
658 );
659 }
660}