Skip to main content

rustafari_core/
lib.rs

1//! Offline developer utilities, free of any UI dependency.
2//!
3//! Everything here is pure and synchronous: no network, no filesystem, no
4//! globals. The GUI is one consumer; a CLI or a test harness could be another.
5//!
6//! ## Adding a tool
7//!
8//! 1. Write `src/tools/<name>.rs` with a unit struct that implements [`Tool`].
9//! 2. Register it in the `mod tools` list and in [`all_tools`].
10//!
11//! There is no third step — the frontend renders whatever options the tool
12//! declares.
13
14mod spec;
15mod tools;
16
17pub use spec::{
18    Category, Format, Input, InputMode, OptionPane, OptionSpec, OptionValue, Options, Tool,
19    ToolError, ToolMeta, ToolResult,
20};
21
22/// Every tool the app ships, in menu order.
23///
24/// This is the example on the crate's README; it is duplicated here so that
25/// `cargo test` catches it drifting from the real signatures.
26///
27/// ```
28/// use rustafari_core::{all_tools, Options};
29///
30/// let tools = all_tools();
31/// let json = &tools[0];
32/// let opts = Options::from_specs(json.options());
33///
34/// assert_eq!(json.run(r#"{"a":1}"#.into(), &opts).unwrap(), "{\n  \"a\": 1\n}");
35/// ```
36pub fn all_tools() -> Vec<Box<dyn Tool>> {
37    vec![
38        Box::new(tools::json::JsonFormatter),
39        Box::new(tools::json_diff::JsonDiff),
40        Box::new(tools::yaml_diff::YamlDiff),
41        Box::new(tools::xml_diff::XmlDiff),
42        Box::new(tools::base64::Base64Tool),
43        Box::new(tools::url::UrlTool),
44        Box::new(tools::hash::HashTool),
45        Box::new(tools::uuid::UuidTool),
46        Box::new(tools::cron::Cron),
47        Box::new(tools::list_compare::ListCompare),
48    ]
49}
50
51/// Case-insensitive match against a tool's name, description and keywords.
52pub fn matches_query(meta: &ToolMeta, query: &str) -> bool {
53    let query = query.trim().to_lowercase();
54    if query.is_empty() {
55        return true;
56    }
57
58    query.split_whitespace().all(|term| {
59        meta.name.to_lowercase().contains(term)
60            || meta.description.to_lowercase().contains(term)
61            || meta.keywords.iter().any(|k| k.contains(term))
62    })
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    use std::collections::HashSet;
69
70    #[test]
71    fn tool_ids_are_unique() {
72        let tools = all_tools();
73        let ids: HashSet<_> = tools.iter().map(|t| t.meta().id).collect();
74        assert_eq!(ids.len(), tools.len(), "duplicate tool id");
75    }
76
77    #[test]
78    fn every_declared_option_has_a_usable_default() {
79        for tool in all_tools() {
80            let specs = tool.options();
81            let opts = Options::from_specs(specs);
82            for spec in specs.iter().filter(|s| s.is_value()) {
83                assert!(
84                    opts.get(spec.id()).is_some(),
85                    "{} option {} has no default",
86                    tool.meta().id,
87                    spec.id()
88                );
89            }
90            // Empty input under default options is exactly what the user sees
91            // when they open a tool, so it must never be an error.
92            assert!(
93                tool.run(Input::default(), &opts).is_ok(),
94                "{}",
95                tool.meta().id
96            );
97        }
98    }
99
100    #[test]
101    fn choice_defaults_name_a_real_choice() {
102        for tool in all_tools() {
103            for spec in tool.options() {
104                if let OptionSpec::Choice {
105                    id,
106                    choices,
107                    default,
108                    ..
109                } = spec
110                {
111                    assert!(
112                        choices.iter().any(|(value, _)| value == default),
113                        "{}.{id} defaults to {default}, which is not a choice",
114                        tool.meta().id
115                    );
116                }
117            }
118        }
119    }
120
121    /// The chaining menu is only worth having if it refuses links that cannot
122    /// work, and only usable if it keeps the ones that can. Both halves have
123    /// bitten: an unfiltered menu offered "send this list to the JSON
124    /// formatter", and an over-eager filter would drop decode-then-pretty-print,
125    /// which is the chain the feature exists for.
126    #[test]
127    fn chaining_refuses_impossible_links_and_keeps_possible_ones() {
128        let tools = all_tools();
129        let by_id = |id: &str| {
130            tools
131                .iter()
132                .find(|t| t.meta().id == id)
133                .expect("tool exists")
134        };
135
136        let json = by_id("json-formatter");
137        let list = by_id("list-compare");
138        let base64 = by_id("base64");
139
140        // A list of names is not a JSON document.
141        let list_opts = Options::from_specs(list.options());
142        assert!(!list.produces(&list_opts).flows_into(json.accepts()));
143
144        // ...but asking List Compare for JSON output makes it one.
145        let mut as_json = Options::from_specs(list.options());
146        as_json.set("format", OptionValue::Choice("json".into()));
147        assert!(list.produces(&as_json).flows_into(json.accepts()));
148
149        // Base64 *decode* has no idea what it produced, so it must not be
150        // pruned: decode-then-format is the everyday chain.
151        let mut decode = Options::from_specs(base64.options());
152        decode.set("direction", OptionValue::Choice("decode".into()));
153        assert!(base64.produces(&decode).flows_into(json.accepts()));
154
155        // Encoding, though, is known to be Base64 and known not to be JSON.
156        let encode = Options::from_specs(base64.options());
157        assert!(!base64.produces(&encode).flows_into(json.accepts()));
158
159        // Every tool that takes input must accept something.
160        for tool in &tools {
161            if tool.input_mode() != InputMode::None {
162                assert!(!tool.accepts().is_empty(), "{}", tool.meta().id);
163            }
164        }
165    }
166
167    #[test]
168    fn search_matches_name_and_keywords_and_requires_all_terms() {
169        let tools = all_tools();
170        let json = tools[0].meta();
171        assert!(matches_query(&json, ""));
172        assert!(matches_query(&json, "JSON"));
173        assert!(matches_query(&json, "beautify"));
174        assert!(matches_query(&json, "json minify"));
175        assert!(!matches_query(&json, "json sha"));
176    }
177}