agent_commander/tools/
shell.rs1pub fn escape_arg(arg: &str) -> String {
5 if arg.is_empty()
6 || !arg
7 .chars()
8 .all(|c| c.is_ascii_alphanumeric() || "-_./:=+,@%".contains(c))
9 {
10 let escaped = arg
11 .replace('\\', "\\\\")
12 .replace('"', "\\\"")
13 .replace('$', "\\$")
14 .replace('`', "\\`");
15 format!("\"{}\"", escaped)
16 } else {
17 arg.to_string()
18 }
19}
20
21pub fn escape_single_quotes(s: &str) -> String {
24 command_stream::quote::escape_for_single_quotes(s)
25}
26
27pub fn lookup_model_alias(
30 model_map: &std::collections::HashMap<&'static str, &'static str>,
31 model: &str,
32) -> Option<String> {
33 model_map
34 .get(model)
35 .or_else(|| {
36 model_map
37 .iter()
38 .find(|(alias, _)| alias.eq_ignore_ascii_case(model))
39 .map(|(_, id)| id)
40 })
41 .map(|id| (*id).to_string())
42}
43
44pub fn is_valid_env_name(name: &str) -> bool {
45 let mut chars = name.chars();
46 let Some(first) = chars.next() else {
47 return false;
48 };
49 if first != '_' && !first.is_ascii_alphabetic() {
50 return false;
51 }
52 chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
53}
54
55pub fn file_content_arg(flag: &str, file: &str) -> String {
58 format!("{} \"$(cat {})\"", flag, escape_arg(file))
59}
60
61#[derive(Debug, Clone, Default, PartialEq, Eq)]
63pub enum InheritEnv {
64 #[default]
66 All,
67 None,
69 Only(Vec<String>),
71}
72
73pub fn build_child_environment(
82 parent: impl IntoIterator<Item = (String, String)>,
83 inherit_env: &InheritEnv,
84 env: Option<&[(String, String)]>,
85 unset_env: &[String],
86 extra_env: &[(String, String)],
87) -> Result<Vec<(String, String)>, String> {
88 let check = |name: &str| {
89 if is_valid_env_name(name) {
90 Ok(())
91 } else {
92 Err(format!("invalid environment variable name: {name}"))
93 }
94 };
95 let mut result: Vec<(String, String)> = match env {
96 Some(env) => env.to_vec(),
97 None => match inherit_env {
98 InheritEnv::All => parent.into_iter().collect(),
99 InheritEnv::None => Vec::new(),
100 InheritEnv::Only(names) => {
101 for name in names {
102 check(name)?;
103 }
104 parent
105 .into_iter()
106 .filter(|(key, _)| names.contains(key))
107 .collect()
108 }
109 },
110 };
111 for name in unset_env {
112 check(name)?;
113 result.retain(|(key, _)| key != name);
114 }
115 for (key, value) in extra_env {
116 check(key)?;
117 result.retain(|(existing, _)| existing != key);
118 result.push((key.clone(), value.clone()));
119 }
120 Ok(result)
121}
122
123pub fn build_command_head(
126 executable: &str,
127 unset_env: &[String],
128 extra_env: &[(String, String)],
129 prefix_args: &[String],
130) -> String {
131 let mut parts = Vec::new();
132
133 if !extra_env.is_empty() || !unset_env.is_empty() {
134 parts.push("env".to_string());
135 for key in unset_env {
136 assert!(
137 is_valid_env_name(key),
138 "invalid environment variable name: {}",
139 key
140 );
141 parts.push(format!("-u {key}"));
142 }
143 for (key, value) in extra_env {
144 assert!(
145 is_valid_env_name(key),
146 "invalid environment variable name: {}",
147 key
148 );
149 parts.push(format!("{}={}", key, escape_arg(value)));
150 }
151 }
152
153 parts.push(escape_arg(executable));
154 parts.extend(prefix_args.iter().map(|arg| escape_arg(arg)));
155 parts.join(" ")
156}