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 build_child_environment_passing(parent, inherit_env, env, &[], unset_env, extra_env)
89}
90
91pub fn build_child_environment_passing(
101 parent: impl IntoIterator<Item = (String, String)>,
102 inherit_env: &InheritEnv,
103 env: Option<&[(String, String)]>,
104 pass_env: &[String],
105 unset_env: &[String],
106 extra_env: &[(String, String)],
107) -> Result<Vec<(String, String)>, String> {
108 let check = |name: &str| {
109 if is_valid_env_name(name) {
110 Ok(())
111 } else {
112 Err(format!("invalid environment variable name: {name}"))
113 }
114 };
115 let parent: Vec<(String, String)> = parent.into_iter().collect();
116 let mut result: Vec<(String, String)> = match env {
117 Some(env) => env.to_vec(),
118 None => match inherit_env {
119 InheritEnv::All => parent.clone(),
120 InheritEnv::None => Vec::new(),
121 InheritEnv::Only(names) => {
122 for name in names {
123 check(name)?;
124 }
125 parent
126 .iter()
127 .filter(|(key, _)| names.contains(key))
128 .cloned()
129 .collect()
130 }
131 },
132 };
133 for name in pass_env {
134 check(name)?;
135 if !result.iter().any(|(key, _)| key == name) {
136 if let Some(entry) = parent.iter().find(|(key, _)| key == name) {
137 result.push(entry.clone());
138 }
139 }
140 }
141 for name in unset_env {
142 check(name)?;
143 result.retain(|(key, _)| key != name);
144 }
145 for (key, value) in extra_env {
146 check(key)?;
147 result.retain(|(existing, _)| existing != key);
148 result.push((key.clone(), value.clone()));
149 }
150 Ok(result)
151}
152
153pub fn build_command_head(
156 executable: &str,
157 unset_env: &[String],
158 extra_env: &[(String, String)],
159 prefix_args: &[String],
160) -> String {
161 let mut parts = Vec::new();
162
163 if !extra_env.is_empty() || !unset_env.is_empty() {
164 parts.push("env".to_string());
165 for key in unset_env {
166 assert!(
167 is_valid_env_name(key),
168 "invalid environment variable name: {}",
169 key
170 );
171 parts.push(format!("-u {key}"));
172 }
173 for (key, value) in extra_env {
174 assert!(
175 is_valid_env_name(key),
176 "invalid environment variable name: {}",
177 key
178 );
179 parts.push(format!("{}={}", key, escape_arg(value)));
180 }
181 }
182
183 parts.push(escape_arg(executable));
184 parts.extend(prefix_args.iter().map(|arg| escape_arg(arg)));
185 parts.join(" ")
186}