Skip to main content

artifactize_tools/builtin/
input.rs

1//! Parse schema-validated provider arguments once, before builtin execution.
2use 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    /// CLI values enter the same compiled domain as provider input, without JSON round trips.
21    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::Graph | Builtin::Section | Builtin::Help | Builtin::Open => {
43                return Err("This builtin requires declared args.".into());
44            }
45            Builtin::Read => serde_json::from_value(value).map(Self::Read),
46            Builtin::List => serde_json::from_value(value).map(Self::List),
47            Builtin::Glob => serde_json::from_value(value).map(Self::Glob),
48            Builtin::Grep => serde_json::from_value(value).map(Self::Grep),
49            Builtin::ViewImage => serde_json::from_value(value).map(Self::ViewImage),
50        };
51        input.map_err(|error| error.to_string())
52    }
53}
54
55#[derive(Debug, Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct Read {
58    pub path: LogicalPath,
59    #[serde(default = "first_line", deserialize_with = "integer")]
60    pub offset: usize,
61    #[serde(default = "read_lines", deserialize_with = "integer")]
62    pub limit: usize,
63}
64#[derive(Debug, Deserialize)]
65#[serde(deny_unknown_fields)]
66pub struct List {
67    #[serde(default)]
68    pub path: LogicalPath,
69    #[serde(default, deserialize_with = "integer")]
70    pub offset: usize,
71    #[serde(default = "max_results", deserialize_with = "integer")]
72    pub limit: usize,
73}
74#[derive(Debug, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub struct Glob {
77    #[serde(deserialize_with = "glob_pattern")]
78    pub pattern: GlobMatcher,
79    #[serde(default)]
80    pub path: LogicalPath,
81}
82#[derive(Debug)]
83pub struct Grep {
84    pub pattern: Regex,
85    pub path: LogicalPath,
86    pub glob: Option<GlobMatcher>,
87    pub max_results: usize,
88}
89impl<'de> Deserialize<'de> for Grep {
90    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
91        #[derive(Deserialize)]
92        #[serde(rename_all = "camelCase", deny_unknown_fields)]
93        struct Arguments {
94            pattern: String,
95            #[serde(default)]
96            path: LogicalPath,
97            #[serde(default)]
98            glob: Option<String>,
99            #[serde(default)]
100            case_insensitive: bool,
101            #[serde(default = "max_results", deserialize_with = "integer")]
102            max_results: usize,
103        }
104        let args = Arguments::deserialize(deserializer)?;
105        Self::new(
106            &args.pattern,
107            args.path,
108            args.glob.as_deref(),
109            args.case_insensitive,
110            args.max_results,
111        )
112        .map_err(de::Error::custom)
113    }
114}
115
116impl Grep {
117    fn new(
118        pattern: &str,
119        path: LogicalPath,
120        glob: Option<&str>,
121        insensitive: bool,
122        max_results: usize,
123    ) -> Result<Self, String> {
124        pattern_size(pattern)?;
125        if let Some(glob) = glob {
126            pattern_size(glob)?;
127        }
128        let pattern = RegexBuilder::new(pattern)
129            .case_insensitive(insensitive)
130            .size_limit(super::REGEX_BYTES)
131            .build()
132            .map_err(|_| "Invalid or oversized regex pattern.".to_owned())?;
133        Ok(Self {
134            pattern,
135            path,
136            glob: glob.map(super::glob).transpose()?,
137            max_results,
138        })
139    }
140}
141
142fn pattern_size(pattern: &str) -> Result<(), String> {
143    if pattern.is_empty() || pattern.chars().count() > super::MAX_PATTERN_UNITS {
144        Err("Pattern must be nonempty and fit the declared pattern limit.".into())
145    } else {
146        Ok(())
147    }
148}
149
150/// Validated arguments carry either a logical path or the legacy selective-root alias.
151#[derive(Debug)]
152pub struct LogicalPath(Option<InputPath<String>>);
153impl Default for LogicalPath {
154    fn default() -> Self {
155        Self(Some(InputPath::root().owned()))
156    }
157}
158impl LogicalPath {
159    /// A native command-line path, validated once at the edge.
160    pub(crate) fn from_native(path: &std::path::Path) -> Result<Self, String> {
161        InputPath::from_native(path)
162            .map(|path| Self(Some(path)))
163            .map_err(|error| error.to_string())
164    }
165
166    pub fn parse(path: String) -> Result<Self, String> {
167        if path == "." {
168            return Ok(Self(None));
169        }
170        InputPath::parse(path)
171            .map(|path| Self(Some(path)))
172            .map_err(|error| error.to_string())
173    }
174
175    /// Dot is accepted only by listing/search on a selective owner. Check the owner
176    /// fallibly so an unknown owner gives the same error as it would for a real path.
177    pub(crate) fn resolve<'a>(
178        &'a self,
179        scope: &Scope,
180        owner: &ArtifactId,
181        allow_dot: bool,
182    ) -> Result<InputPath<&'a str>, String> {
183        if let Some(path) = &self.0 {
184            return Ok(path.borrowed());
185        }
186        if allow_dot
187            && scope
188                .artifact(owner)
189                .map_err(|error| error.to_string())?
190                .selective()
191        {
192            return Ok(InputPath::root());
193        }
194        Err("Artifact path must be a safe relative logical path.".into())
195    }
196}
197impl<'de> Deserialize<'de> for LogicalPath {
198    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
199        let path = String::deserialize(deserializer)?;
200        Self::parse(path).map_err(de::Error::custom)
201    }
202}
203
204fn glob_pattern<'de, D: Deserializer<'de>>(deserializer: D) -> Result<GlobMatcher, D::Error> {
205    super::glob(&String::deserialize(deserializer)?).map_err(de::Error::custom)
206}
207
208#[derive(Debug, Deserialize)]
209#[serde(deny_unknown_fields)]
210pub struct ViewImage {
211    pub path: LogicalPath,
212}
213
214fn first_line() -> usize {
215    super::FIRST_LINE
216}
217fn read_lines() -> usize {
218    super::DEFAULT_READ_LINES
219}
220fn max_results() -> usize {
221    super::MAX_RESULTS
222}
223
224/// JSON Schema treats 1 and 1.0 as the same integer. Preserve the validator's numeric
225/// semantics and the previous saturating usize conversion, including 32-bit hosts.
226fn integer<'de, D: Deserializer<'de>>(deserializer: D) -> Result<usize, D::Error> {
227    struct Integer;
228    impl de::Visitor<'_> for Integer {
229        type Value = usize;
230        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231            formatter.write_str("a nonnegative safe JSON integer")
232        }
233        fn visit_u64<E: de::Error>(self, value: u64) -> Result<usize, E> {
234            self.visit_f64(value as f64)
235        }
236        fn visit_i64<E: de::Error>(self, value: i64) -> Result<usize, E> {
237            self.visit_f64(value as f64)
238        }
239        fn visit_f64<E: de::Error>(self, value: f64) -> Result<usize, E> {
240            if value.is_finite()
241                && value >= 0.0
242                && value.fract() == 0.0
243                && value <= crate::MAX_SAFE_JSON_INTEGER as f64
244            {
245                Ok(value as usize)
246            } else {
247                Err(E::custom("expected a nonnegative safe JSON integer"))
248            }
249        }
250    }
251    deserializer.deserialize_any(Integer)
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use serde_json::json;
258
259    #[test]
260    fn edge_rejects_out_of_range_and_unknown_arguments_without_caller_validation() {
261        for (builtin, value) in [
262            (Builtin::Read, json!({"path":"notes", "offset":0})),
263            (Builtin::Read, json!({"path":"notes", "limit":501})),
264            (Builtin::List, json!({"limit":201})),
265            (Builtin::Grep, json!({"pattern":"notes", "maxResults":0})),
266            (Builtin::Glob, json!({"pattern":""})),
267            (Builtin::Read, json!({"path":"../notes"})),
268            (Builtin::List, json!({"path":"nested//notes"})),
269            (Builtin::Glob, json!({"pattern":"../*"})),
270            (Builtin::Grep, json!({"pattern":"["})),
271            (Builtin::Grep, json!({"pattern":"notes", "glob":"../*"})),
272            (Builtin::ViewImage, json!({"path":"image", "unknown":true})),
273        ] {
274            assert!(Input::parse(builtin, value).is_err());
275        }
276        let parsed = Input::parse(
277            Builtin::Read,
278            json!({"path":"notes", "offset":1.0, "limit":2.0}),
279        )
280        .unwrap();
281        let Input::Read(input) = parsed else {
282            panic!("expected a read input")
283        };
284        assert_eq!((input.offset, input.limit), (1, 2));
285    }
286}