sherpack-engine 0.4.0

Jinja2 templating engine for Sherpack with Kubernetes-specific filters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Fuzzy matching and context-aware suggestions for template errors
//!
//! This module provides intelligent suggestions when template errors occur,
//! using Levenshtein distance for fuzzy matching and context extraction
//! to help users fix common mistakes.

use serde_json::Value as JsonValue;

/// Maximum Levenshtein distance to consider for suggestions
const MAX_SUGGESTION_DISTANCE: usize = 3;

/// All registered filters in the engine
pub const AVAILABLE_FILTERS: &[&str] = &[
    // Custom Sherpack filters
    "toyaml",
    "tojson",
    "tojson_pretty",
    "b64encode",
    "b64decode",
    "quote",
    "squote",
    "nindent",
    "indent",
    "required",
    "empty",
    "haskey",
    "keys",
    "merge",
    "sha256",
    "trunc",
    "trimprefix",
    "trimsuffix",
    "snakecase",
    "kebabcase",
    "tostrings", // Convert list elements to strings
    // Built-in MiniJinja filters
    "default",
    "upper",
    "lower",
    "title",
    "capitalize",
    "replace",
    "trim",
    "join",
    "first",
    "last",
    "length",
    "reverse",
    "sort",
    "unique",
    "map",
    "select",
    "reject",
    "selectattr",
    "rejectattr",
    "batch",
    "slice",
    "dictsort",
    "items",
    "attr",
    "int",
    "float",
    "abs",
    "round",
    "string",
    "list",
    "bool",
    "safe",
    "escape",
    "e",
    "urlencode",
];

/// All registered functions in the engine
pub const AVAILABLE_FUNCTIONS: &[&str] = &[
    // Custom Sherpack functions
    "fail",
    "dict",
    "list",
    "get",
    "coalesce",
    "ternary",
    "uuidv4",
    "tostring",
    "toint",
    "tofloat",
    "now",
    "printf",
    "tpl",     // Dynamic template evaluation
    "tpl_ctx", // Dynamic template with full context
    "lookup",  // K8s resource lookup (returns empty in template mode)
    // Built-in MiniJinja globals
    "range",
    "lipsum",
    "cycler",
    "joiner",
    "namespace",
];

/// Top-level context variables always available in templates
pub const CONTEXT_VARIABLES: &[&str] = &["values", "release", "pack", "capabilities", "template"];

/// Suggestion result with confidence scoring
#[derive(Debug, Clone)]
pub struct Suggestion {
    /// The suggested correction
    pub text: String,
    /// Levenshtein distance (lower = better match)
    pub distance: usize,
    /// Category of suggestion
    pub category: SuggestionCategory,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SuggestionCategory {
    Variable,
    Filter,
    Function,
    Property,
}

/// Calculate Levenshtein distance between two strings
pub fn levenshtein(a: &str, b: &str) -> usize {
    strsim::levenshtein(a, b)
}

/// Find closest matches from a list of candidates
pub fn find_closest_matches(
    input: &str,
    candidates: &[&str],
    max_results: usize,
    category: SuggestionCategory,
) -> Vec<Suggestion> {
    let mut suggestions: Vec<Suggestion> = candidates
        .iter()
        .filter_map(|&candidate| {
            let distance = levenshtein(input, candidate);
            if distance <= MAX_SUGGESTION_DISTANCE && distance > 0 {
                Some(Suggestion {
                    text: candidate.to_string(),
                    distance,
                    category,
                })
            } else {
                None
            }
        })
        .collect();

    // Sort by distance (best matches first)
    suggestions.sort_by_key(|s| s.distance);
    suggestions.truncate(max_results);
    suggestions
}

/// Suggest corrections for an undefined variable
pub fn suggest_undefined_variable(
    variable_name: &str,
    available_variables: &[String],
) -> Option<String> {
    // First check for common typo: "value" instead of "values"
    if variable_name == "value" {
        return Some(
            "Did you mean `values`? The values object is accessed as `values.key`".to_string(),
        );
    }

    // Check top-level context variables
    let context_match = find_closest_matches(
        variable_name,
        CONTEXT_VARIABLES,
        1,
        SuggestionCategory::Variable,
    );

    if let Some(suggestion) = context_match.first() {
        return Some(format!("Did you mean `{}`?", suggestion.text));
    }

    // Check available values
    let candidates: Vec<&str> = available_variables.iter().map(|s| s.as_str()).collect();

    let value_match =
        find_closest_matches(variable_name, &candidates, 3, SuggestionCategory::Variable);

    if !value_match.is_empty() {
        let suggestions: Vec<String> = value_match
            .iter()
            .map(|s| format!("`{}`", s.text))
            .collect();
        Some(format!("Did you mean {}?", suggestions.join(" or ")))
    } else {
        None
    }
}

/// Suggest corrections for an unknown filter
pub fn suggest_unknown_filter(filter_name: &str) -> Option<String> {
    let matches = find_closest_matches(
        filter_name,
        AVAILABLE_FILTERS,
        3,
        SuggestionCategory::Filter,
    );

    if !matches.is_empty() {
        let suggestions: Vec<String> = matches.iter().map(|s| format!("`{}`", s.text)).collect();
        Some(format!(
            "Did you mean {}? Common filters: toyaml, tojson, b64encode, quote, default, indent",
            suggestions.join(" or ")
        ))
    } else {
        Some(format!(
            "Unknown filter `{}`. Common filters: toyaml, tojson, b64encode, quote, default, indent, nindent",
            filter_name
        ))
    }
}

/// Suggest corrections for an unknown function
pub fn suggest_unknown_function(func_name: &str) -> Option<String> {
    let matches = find_closest_matches(
        func_name,
        AVAILABLE_FUNCTIONS,
        3,
        SuggestionCategory::Function,
    );

    if !matches.is_empty() {
        let suggestions: Vec<String> = matches.iter().map(|s| format!("`{}`", s.text)).collect();
        Some(format!("Did you mean {}?", suggestions.join(" or ")))
    } else {
        Some(format!(
            "Unknown function `{}`. Available functions: {}",
            func_name,
            AVAILABLE_FUNCTIONS.join(", ")
        ))
    }
}

/// Extract available keys from a JSON value at a given path
pub fn extract_available_keys(values: &JsonValue, path: &str) -> Vec<String> {
    let parts: Vec<&str> = path.split('.').filter(|s| !s.is_empty()).collect();

    let mut current = values;
    for part in &parts {
        match current.get(part) {
            Some(v) => current = v,
            None => return vec![],
        }
    }

    match current {
        JsonValue::Object(map) => map.keys().cloned().collect(),
        _ => vec![],
    }
}

/// Suggest available properties when accessing undefined key
pub fn suggest_available_properties(
    parent_path: &str,
    attempted_key: &str,
    values: &JsonValue,
) -> Option<String> {
    let available = extract_available_keys(values, parent_path);

    if available.is_empty() {
        return None;
    }

    // Try fuzzy match first
    let candidates: Vec<&str> = available.iter().map(|s| s.as_str()).collect();
    let matches = find_closest_matches(attempted_key, &candidates, 3, SuggestionCategory::Property);

    if !matches.is_empty() {
        let suggestions: Vec<String> = matches
            .iter()
            .map(|s| format!("`{}.{}`", parent_path, s.text))
            .collect();
        Some(format!(
            "Did you mean {}? Available: {}",
            suggestions.join(" or "),
            available.join(", ")
        ))
    } else {
        Some(format!(
            "Key `{}` not found in `{}`. Available keys: {}",
            attempted_key,
            parent_path,
            available.join(", ")
        ))
    }
}

/// Generate a type-specific hint for iteration errors
pub fn suggest_iteration_fix(type_name: &str) -> String {
    match type_name {
        "object" | "map" => {
            "Objects require `| dictsort` to iterate: `{% for key, value in obj | dictsort %}`"
                .to_string()
        }
        "string" => {
            "Strings iterate character by character. Did you mean to split it first?".to_string()
        }
        "null" | "none" => {
            "Value is null/undefined. Check that it exists or use `| default([])` for empty list"
                .to_string()
        }
        _ => format!(
            "Value of type `{}` is not iterable. Use a list or add `| dictsort` for objects",
            type_name
        ),
    }
}

/// Extract variable name from error message
pub fn extract_variable_name(msg: &str) -> Option<String> {
    // Pattern: "undefined variable `foo`" or "variable 'foo' is undefined"
    let patterns = [("`", "`"), ("'", "'"), ("\"", "\"")];

    for (start, end) in patterns {
        if let Some(start_idx) = msg.find(start) {
            let rest = &msg[start_idx + start.len()..];
            if let Some(end_idx) = rest.find(end) {
                return Some(rest[..end_idx].to_string());
            }
        }
    }
    None
}

/// Extract filter name from error message
pub fn extract_filter_name(msg: &str) -> Option<String> {
    extract_variable_name(msg)
}

/// Extract function name from error message
pub fn extract_function_name(msg: &str) -> Option<String> {
    extract_variable_name(msg)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_levenshtein_distance() {
        assert_eq!(levenshtein("value", "values"), 1);
        assert_eq!(levenshtein("toyml", "toyaml"), 1);
        assert_eq!(levenshtein("b64encode", "b64encode"), 0);
        // strsim calculates actual Levenshtein distance = 7
        assert_eq!(levenshtein("something", "completely"), 7);
    }

    #[test]
    fn test_find_closest_matches() {
        let matches =
            find_closest_matches("toyml", AVAILABLE_FILTERS, 3, SuggestionCategory::Filter);
        assert!(!matches.is_empty());
        assert_eq!(matches[0].text, "toyaml");
        assert_eq!(matches[0].distance, 1);
    }

    #[test]
    fn test_suggest_undefined_variable_typo() {
        let suggestion = suggest_undefined_variable("value", &[]);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("values"));
    }

    #[test]
    fn test_suggest_unknown_filter() {
        let suggestion = suggest_unknown_filter("toyml");
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("toyaml"));
    }

    #[test]
    fn test_extract_available_keys() {
        let values = serde_json::json!({
            "image": {
                "repository": "nginx",
                "tag": "latest"
            },
            "replicas": 3
        });

        let keys = extract_available_keys(&values, "image");
        assert!(keys.contains(&"repository".to_string()));
        assert!(keys.contains(&"tag".to_string()));
    }

    #[test]
    fn test_extract_variable_name() {
        assert_eq!(
            extract_variable_name("undefined variable `foo`"),
            Some("foo".to_string())
        );
        assert_eq!(
            extract_variable_name("variable 'bar' is undefined"),
            Some("bar".to_string())
        );
    }
}