artifactize_tools/builtin/
input.rs1use crate::{
3 Builtin,
4 scope::{ArtifactId, InputPath, Scope},
5};
6use globset::GlobMatcher;
7use regex::{Regex, RegexBuilder};
8use serde::{Deserialize, Deserializer, de};
9use serde_json::Value;
10
11#[derive(Debug)]
12pub enum Input {
13 Read(Read),
14 List(List),
15 Glob(Glob),
16 Grep(Grep),
17 ViewImage(ViewImage),
18}
19impl Input {
20 pub(crate) fn glob(pattern: &str, path: LogicalPath) -> Result<Self, String> {
22 pattern_size(pattern)?;
23 Ok(Self::Glob(Glob {
24 pattern: super::glob(pattern)?,
25 path,
26 }))
27 }
28
29 pub(crate) fn grep(
30 pattern: &str,
31 path: LogicalPath,
32 glob: Option<&str>,
33 insensitive: bool,
34 ) -> Result<Self, String> {
35 Grep::new(pattern, path, glob, insensitive, super::MAX_RESULTS).map(Self::Grep)
36 }
37
38 pub fn parse(builtin: Builtin, value: Value) -> Result<Self, String> {
39 let validator = crate::schema::compile(&super::input_schema(builtin))?;
40 crate::schema::validate(&validator, &value)?;
41 let input = match builtin {
42 Builtin::Declarations
43 | Builtin::Graph
44 | Builtin::Section
45 | Builtin::Help
46 | Builtin::Open => {
47 return Err("This builtin requires declared args.".into());
48 }
49 Builtin::Read => serde_json::from_value(value).map(Self::Read),
50 Builtin::List => serde_json::from_value(value).map(Self::List),
51 Builtin::Glob => serde_json::from_value(value).map(Self::Glob),
52 Builtin::Grep => serde_json::from_value(value).map(Self::Grep),
53 Builtin::ViewImage => serde_json::from_value(value).map(Self::ViewImage),
54 };
55 input.map_err(|error| error.to_string())
56 }
57}
58
59#[derive(Debug, Deserialize)]
60#[serde(deny_unknown_fields)]
61pub struct Read {
62 pub path: LogicalPath,
63 #[serde(default = "first_line", deserialize_with = "integer")]
64 pub offset: usize,
65 #[serde(default = "read_lines", deserialize_with = "integer")]
66 pub limit: usize,
67}
68#[derive(Debug, Deserialize)]
69#[serde(deny_unknown_fields)]
70pub struct List {
71 #[serde(default)]
72 pub path: LogicalPath,
73 #[serde(default, deserialize_with = "integer")]
74 pub offset: usize,
75 #[serde(default = "max_results", deserialize_with = "integer")]
76 pub limit: usize,
77}
78#[derive(Debug, Deserialize)]
79#[serde(deny_unknown_fields)]
80pub struct Glob {
81 #[serde(deserialize_with = "glob_pattern")]
82 pub pattern: GlobMatcher,
83 #[serde(default)]
84 pub path: LogicalPath,
85}
86#[derive(Debug)]
87pub struct Grep {
88 pub pattern: Regex,
89 pub path: LogicalPath,
90 pub glob: Option<GlobMatcher>,
91 pub max_results: usize,
92}
93impl<'de> Deserialize<'de> for Grep {
94 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
95 #[derive(Deserialize)]
96 #[serde(rename_all = "camelCase", deny_unknown_fields)]
97 struct Arguments {
98 pattern: String,
99 #[serde(default)]
100 path: LogicalPath,
101 #[serde(default)]
102 glob: Option<String>,
103 #[serde(default)]
104 case_insensitive: bool,
105 #[serde(default = "max_results", deserialize_with = "integer")]
106 max_results: usize,
107 }
108 let args = Arguments::deserialize(deserializer)?;
109 Self::new(
110 &args.pattern,
111 args.path,
112 args.glob.as_deref(),
113 args.case_insensitive,
114 args.max_results,
115 )
116 .map_err(de::Error::custom)
117 }
118}
119
120impl Grep {
121 fn new(
122 pattern: &str,
123 path: LogicalPath,
124 glob: Option<&str>,
125 insensitive: bool,
126 max_results: usize,
127 ) -> Result<Self, String> {
128 pattern_size(pattern)?;
129 if let Some(glob) = glob {
130 pattern_size(glob)?;
131 }
132 let pattern = RegexBuilder::new(pattern)
133 .case_insensitive(insensitive)
134 .size_limit(super::REGEX_BYTES)
135 .build()
136 .map_err(|_| "Invalid or oversized regex pattern.".to_owned())?;
137 Ok(Self {
138 pattern,
139 path,
140 glob: glob.map(super::glob).transpose()?,
141 max_results,
142 })
143 }
144}
145
146fn pattern_size(pattern: &str) -> Result<(), String> {
147 if pattern.is_empty() || pattern.chars().count() > super::MAX_PATTERN_UNITS {
148 Err("Pattern must be nonempty and fit the declared pattern limit.".into())
149 } else {
150 Ok(())
151 }
152}
153
154#[derive(Debug)]
156pub struct LogicalPath(Option<InputPath<String>>);
157impl Default for LogicalPath {
158 fn default() -> Self {
159 Self(Some(InputPath::root().owned()))
160 }
161}
162impl LogicalPath {
163 pub(crate) fn from_native(path: &std::path::Path) -> Result<Self, String> {
165 InputPath::from_native(path)
166 .map(|path| Self(Some(path)))
167 .map_err(|error| error.to_string())
168 }
169
170 pub fn parse(path: String) -> Result<Self, String> {
171 if path == "." {
172 return Ok(Self(None));
173 }
174 InputPath::parse(path)
175 .map(|path| Self(Some(path)))
176 .map_err(|error| error.to_string())
177 }
178
179 pub(crate) fn resolve<'a>(
182 &'a self,
183 scope: &Scope,
184 owner: &ArtifactId,
185 allow_dot: bool,
186 ) -> Result<InputPath<&'a str>, String> {
187 if let Some(path) = &self.0 {
188 return Ok(path.borrowed());
189 }
190 if allow_dot
191 && scope
192 .artifact(owner)
193 .map_err(|error| error.to_string())?
194 .selective()
195 {
196 return Ok(InputPath::root());
197 }
198 Err("Artifact path must be a safe relative logical path.".into())
199 }
200}
201impl<'de> Deserialize<'de> for LogicalPath {
202 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
203 let path = String::deserialize(deserializer)?;
204 Self::parse(path).map_err(de::Error::custom)
205 }
206}
207
208fn glob_pattern<'de, D: Deserializer<'de>>(deserializer: D) -> Result<GlobMatcher, D::Error> {
209 super::glob(&String::deserialize(deserializer)?).map_err(de::Error::custom)
210}
211
212#[derive(Debug, Deserialize)]
213#[serde(deny_unknown_fields)]
214pub struct ViewImage {
215 pub path: LogicalPath,
216}
217
218fn first_line() -> usize {
219 super::FIRST_LINE
220}
221fn read_lines() -> usize {
222 super::DEFAULT_READ_LINES
223}
224fn max_results() -> usize {
225 super::MAX_RESULTS
226}
227
228fn integer<'de, D: Deserializer<'de>>(deserializer: D) -> Result<usize, D::Error> {
231 struct Integer;
232 impl de::Visitor<'_> for Integer {
233 type Value = usize;
234 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235 formatter.write_str("a nonnegative safe JSON integer")
236 }
237 fn visit_u64<E: de::Error>(self, value: u64) -> Result<usize, E> {
238 self.visit_f64(value as f64)
239 }
240 fn visit_i64<E: de::Error>(self, value: i64) -> Result<usize, E> {
241 self.visit_f64(value as f64)
242 }
243 fn visit_f64<E: de::Error>(self, value: f64) -> Result<usize, E> {
244 if value.is_finite()
245 && value >= 0.0
246 && value.fract() == 0.0
247 && value <= crate::MAX_SAFE_JSON_INTEGER as f64
248 {
249 Ok(value as usize)
250 } else {
251 Err(E::custom("expected a nonnegative safe JSON integer"))
252 }
253 }
254 }
255 deserializer.deserialize_any(Integer)
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261 use serde_json::json;
262
263 #[test]
264 fn edge_rejects_out_of_range_and_unknown_arguments_without_caller_validation() {
265 for (builtin, value) in [
266 (Builtin::Read, json!({"path":"notes", "offset":0})),
267 (Builtin::Read, json!({"path":"notes", "limit":501})),
268 (Builtin::List, json!({"limit":201})),
269 (Builtin::Grep, json!({"pattern":"notes", "maxResults":0})),
270 (Builtin::Glob, json!({"pattern":""})),
271 (Builtin::Read, json!({"path":"../notes"})),
272 (Builtin::List, json!({"path":"nested//notes"})),
273 (Builtin::Glob, json!({"pattern":"../*"})),
274 (Builtin::Grep, json!({"pattern":"["})),
275 (Builtin::Grep, json!({"pattern":"notes", "glob":"../*"})),
276 (Builtin::ViewImage, json!({"path":"image", "unknown":true})),
277 ] {
278 assert!(Input::parse(builtin, value).is_err());
279 }
280 let parsed = Input::parse(
281 Builtin::Read,
282 json!({"path":"notes", "offset":1.0, "limit":2.0}),
283 )
284 .unwrap();
285 let Input::Read(input) = parsed else {
286 panic!("expected a read input")
287 };
288 assert_eq!((input.offset, input.limit), (1, 2));
289 }
290}