BlueGit

ict rusty-teams

Files

rusty-teams / crates / agents / src / template.rs

template.rs

template.rs 5.5 KiB Download Raw
1const PLACEHOLDERS: [&str; 11] = [
2 "message",
3 "sender",
4 "chat",
5 "conversation_id",
6 "message_id",
7 "thread",
8 "extra",
9 "cwd",
10 "session_id",
11 "agent",
12 "prompt",
13];
14
15#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
16#[error("unknown placeholder {{{0}}}")]
17pub struct UnknownPlaceholder(pub String);
18
19#[derive(Clone, Debug, Default)]
20pub struct Values {
21 pub message: String,
22 pub sender: String,
23 pub chat: String,
24 pub conversation_id: String,
25 pub message_id: String,
26 pub thread: String,
27 pub extra: String,
28 pub cwd: String,
29 pub session_id: String,
30 pub agent: String,
31 pub prompt: String,
32}
33
34impl Values {
35 fn get(&self, name: &str) -> Option<&str> {
36 match name {
37 "message" => Some(&self.message),
38 "sender" => Some(&self.sender),
39 "chat" => Some(&self.chat),
40 "conversation_id" => Some(&self.conversation_id),
41 "message_id" => Some(&self.message_id),
42 "thread" => Some(&self.thread),
43 "extra" => Some(&self.extra),
44 "cwd" => Some(&self.cwd),
45 "session_id" => Some(&self.session_id),
46 "agent" => Some(&self.agent),
47 "prompt" => Some(&self.prompt),
48 _ => None,
49 }
50 }
51}
52
53pub(crate) fn is_known_placeholder(name: &str) -> bool {
54 PLACEHOLDERS.contains(&name)
55}
56
57fn next_placeholder(text: &str) -> Option<(usize, usize, &str)> {
58 let mut search_from = 0;
59 while let Some(offset) = text[search_from..].find('{') {
60 let start = search_from + offset;
61 let rest = &text[start + 1..];
62 if let Some(end) = rest.find('}') {
63 let name = &rest[..end];
64 let is_identifier = !name.is_empty()
65 && name
66 .chars()
67 .all(|character| character.is_ascii_alphanumeric() || character == '_');
68 if is_identifier {
69 return Some((start, start + end + 2, name));
70 }
71 }
72 search_from = start + 1;
73 }
74 None
75}
76
77pub fn placeholders_in(template: &str) -> Vec<String> {
78 let mut names = Vec::new();
79 let mut remaining = template;
80 while let Some((_, end, name)) = next_placeholder(remaining) {
81 names.push(name.to_string());
82 remaining = &remaining[end..];
83 }
84 names
85}
86
87pub fn render(template: &str, values: &Values) -> Result<String, UnknownPlaceholder> {
88 let mut output = String::with_capacity(template.len());
89 let mut remaining = template;
90 while let Some((start, end, name)) = next_placeholder(remaining) {
91 let value = values
92 .get(name)
93 .ok_or_else(|| UnknownPlaceholder(name.to_string()))?;
94 output.push_str(&remaining[..start]);
95 output.push_str(value);
96 remaining = &remaining[end..];
97 }
98 output.push_str(remaining);
99 Ok(output)
100}
101
102pub fn split_command(command: &str) -> Vec<String> {
103 let mut tokens = Vec::new();
104 let mut current = String::new();
105 let mut in_token = false;
106 let mut quote: Option<char> = None;
107 for character in command.chars() {
108 match quote {
109 Some(open) if character == open => quote = None,
110 Some(_) => current.push(character),
111 None if character == '"' || character == '\'' => {
112 quote = Some(character);
113 in_token = true;
114 }
115 None if character.is_whitespace() => {
116 if in_token {
117 tokens.push(std::mem::take(&mut current));
118 in_token = false;
119 }
120 }
121 None => {
122 current.push(character);
123 in_token = true;
124 }
125 }
126 }
127 if in_token {
128 tokens.push(current);
129 }
130 tokens
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136
137 fn values() -> Values {
138 Values {
139 sender: "Ada".to_string(),
140 prompt: "line one\nline two".to_string(),
141 session_id: "abc".to_string(),
142 ..Values::default()
143 }
144 }
145
146 #[test]
147 fn renders_known_placeholders() {
148 let rendered = render("{sender} id={session_id} {extra}!", &values()).unwrap();
149 assert_eq!(rendered, "Ada id=abc !");
150 }
151
152 #[test]
153 fn rejects_unknown_placeholder() {
154 let error = render("hello {nope}", &values()).unwrap_err();
155 assert_eq!(error, UnknownPlaceholder("nope".to_string()));
156 }
157
158 #[test]
159 fn keeps_non_placeholder_braces() {
160 assert_eq!(
161 render("{\"a\": 1} { x }", &values()).unwrap(),
162 "{\"a\": 1} { x }"
163 );
164 }
165
166 #[test]
167 fn does_not_rescan_substituted_values() {
168 let mut substituted = values();
169 substituted.sender = "{prompt}".to_string();
170 assert_eq!(render("{sender}", &substituted).unwrap(), "{prompt}");
171 }
172
173 #[test]
174 fn lists_placeholders() {
175 assert_eq!(
176 placeholders_in("a {message} b {x} {message}"),
177 vec!["message", "x", "message"]
178 );
179 }
180
181 #[test]
182 fn splits_with_quotes() {
183 assert_eq!(
184 split_command(r#"sh -c "echo 'a b'" 'c d' "" e"#),
185 vec!["sh", "-c", "echo 'a b'", "c d", "", "e"]
186 );
187 }
188
189 #[test]
190 fn prompt_stays_one_token() {
191 let tokens = split_command("copilot -p {prompt} --x");
192 let rendered: Vec<String> = tokens
193 .iter()
194 .map(|token| render(token, &values()).unwrap())
195 .collect();
196 assert_eq!(rendered, vec!["copilot", "-p", "line one\nline two", "--x"]);
197 }
198}