apimock-routing 5.17.0

Routing model for apimock: rule sets, request matching, and read-only views for GUI tooling.
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Builders that turn the in-memory routing model into the view types
//! a GUI consumes.
//!
//! # Why these aren't `From` impls
//!
//! The view shapes need contextual information the source types don't
//! carry — the `index` field on `RuleSetView` and `RuleView` for
//! example. Free functions taking the index alongside the model keep
//! the call sites explicit and type-checked. A `From<&RuleSet>` impl
//! would have to invent the index (probably defaulting to zero) which
//! is just the kind of silent-bug surface we want to avoid.
//!
//! # Why this is a sibling module rather than baked into `view.rs`
//!
//! `view.rs` is the *type* surface — it must stay stable across
//! routing-crate refactors so a GUI's bindings don't churn. Builders
//! depend on the internal `RuleSet` / `Rule` / `When` shapes which
//! *do* churn. Keeping them in their own module makes the dependency
//! direction obvious: `view::build` may import from anywhere in the
//! crate; `view.rs` itself stays leaf.

use std::path::Path;

use serde_json;

use crate::rule_set::RuleSet;
use crate::rule_set::rule::Rule;
use crate::rule_set::rule::respond::Respond;
use crate::rule_set::rule::when::When;
use crate::rule_set::rule::when::request::Request;
use crate::rule_set::rule::when::request::http_method::HttpMethod;
use crate::rule_set::rule::when::request::rule_op::RuleOp;
use crate::rule_set::rule::when::request::url_path::UrlPathConfig;

use crate::view::{
    BodyConditionView, FileNodeKind, FileNodeView, FileTreeView, HeaderConditionView, RespondView,
    RouteCatalogSnapshot, RuleSetView, RuleView, ScriptRouteView, UrlPathView, WhenView,
};

/// Compose the top-level `RouteCatalogSnapshot` from already-built
/// components. Caller supplies `file_tree` and `script_routes` because
/// the routing crate doesn't know about middleware-file paths or the
/// fallback dir's location — those live in `apimock-config`.
pub fn build_route_catalog(
    rule_sets: &[RuleSet],
    fallback_respond_dir: Option<&str>,
    file_tree: Option<FileTreeView>,
    script_routes: Vec<ScriptRouteView>,
) -> RouteCatalogSnapshot {
    let rule_set_views = rule_sets
        .iter()
        .enumerate()
        .map(|(idx, rs)| build_rule_set_view(rs, idx))
        .collect();

    RouteCatalogSnapshot {
        rule_sets: rule_set_views,
        fallback_respond_dir: fallback_respond_dir.map(str::to_owned),
        file_tree,
        script_routes,
    }
}

pub fn build_rule_set_view(rule_set: &RuleSet, index: usize) -> RuleSetView {
    let (url_prefix, dir_prefix) = match rule_set.prefix.as_ref() {
        Some(p) => (p.url_path_prefix.clone(), p.respond_dir_prefix.clone()),
        None => (None, None),
    };

    RuleSetView {
        index,
        source_path: rule_set.file_path.clone(),
        url_path_prefix: url_prefix,
        respond_dir_prefix: dir_prefix,
        strategy: rule_set.strategy.as_ref().map(|s| s.to_string()),
        rules: rule_set
            .rules
            .iter()
            .enumerate()
            .map(|(idx, r)| build_rule_view(r, idx))
            .collect(),
    }
}

pub fn build_rule_view(rule: &Rule, index: usize) -> RuleView {
    RuleView {
        index,
        priority: rule.priority,
        when: build_when_view(&rule.when),
        respond: build_respond_view(&rule.respond),
    }
}

pub fn build_when_view(when: &When) -> WhenView {
    let req: &Request = &when.request;
    WhenView {
        url_path: build_url_path_view(req.url_path_config.as_ref()),
        method: req.http_method.as_ref().map(http_method_name),
        headers: build_header_condition_views(req.headers.as_ref()),
        body: build_body_condition_views(req.body.as_ref()),
    }
}

fn build_header_condition_views(
    headers: Option<&crate::rule_set::rule::when::request::headers::Headers>,
) -> Vec<HeaderConditionView> {
    use crate::rule_set::rule::when::request::headers::header_operator::HeaderOperator;

    let headers = match headers {
        Some(h) => h,
        None => return Vec::new(),
    };
    // IndexMap preserves insertion (TOML authoring) order — no sort needed.
    headers
        .0
        .iter()
        .map(|(name, stmt)| {
            let op = stmt.op.clone().unwrap_or_default();
            let op_str = op.as_str().to_owned();
            // Presence operators have no meaningful value to display.
            let value = match op {
                HeaderOperator::Exists | HeaderOperator::Absent => None,
                _ => Some(stmt.value.clone()),
            };
            HeaderConditionView {
                name: name.clone(),
                op: op_str,
                value,
            }
        })
        .collect()
}

fn build_body_condition_views(
    body: Option<&crate::rule_set::rule::when::request::body::Body>,
) -> Vec<BodyConditionView> {
    use crate::rule_set::rule::when::request::body::body_kind::BodyKind;
    use crate::rule_set::rule::when::request::body::body_operator::BodyOperator;

    let body = match body {
        Some(b) => b,
        None => return Vec::new(),
    };

    let mut views: Vec<BodyConditionView> = Vec::new();
    for (kind, conditions) in &body.0 {
        let kind_str = match kind {
            BodyKind::Json => "json",
        };
        for (path, stmt) in conditions {
            let op_str = format!("{}", stmt.op.as_ref().unwrap_or(&BodyOperator::Equal))
                .trim()
                .to_owned();
            // Normalise the op display string to snake_case form matching
            // the serde rename: strip surrounding spaces, lower-case.
            let op_clean = body_op_name(stmt.op.as_ref().unwrap_or(&BodyOperator::Equal));
            // value: try to parse as JSON; fall back to JSON string.
            let value = serde_json::from_str::<serde_json::Value>(&stmt.value)
                .unwrap_or_else(|_| serde_json::Value::String(stmt.value.clone()));
            let _ = op_str; // suppress unused warning
            views.push(BodyConditionView {
                kind: kind_str.to_owned(),
                path: path.clone(),
                op: op_clean,
                value,
            });
        }
    }
    // Stable order: alphabetical by path.
    views.sort_by(|a, b| a.path.cmp(&b.path));
    views
}

/// Public wrapper so `toml_writer` can serialise body operators to
/// TOML `op` strings without importing routing-internal types.
pub fn body_op_name_pub(
    op: &crate::rule_set::rule::when::request::body::body_operator::BodyOperator,
) -> String {
    body_op_name(op)
}

fn body_op_name(
    op: &crate::rule_set::rule::when::request::body::body_operator::BodyOperator,
) -> String {
    use crate::rule_set::rule::when::request::body::body_operator::BodyOperator;
    match op {
        BodyOperator::Equal => "equal",
        BodyOperator::EqualString => "equal_string",
        BodyOperator::Contains => "contains",
        BodyOperator::NotContains => "not_contains",
        BodyOperator::StartsWith => "starts_with",
        BodyOperator::NotStartsWith => "not_starts_with",
        BodyOperator::EndsWith => "ends_with",
        BodyOperator::NotEndsWith => "not_ends_with",
        BodyOperator::Regex => "regex",
        BodyOperator::NotRegex => "not_regex",
        BodyOperator::EqualTyped => "equal_typed",
        BodyOperator::EqualNumber => "equal_number",
        BodyOperator::GreaterThan => "greater_than",
        BodyOperator::LessThan => "less_than",
        BodyOperator::GreaterOrEqual => "greater_or_equal",
        BodyOperator::LessOrEqual => "less_or_equal",
        BodyOperator::Exists => "exists",
        BodyOperator::Absent => "absent",
        BodyOperator::ArrayLengthEqual => "array_length_equal",
        BodyOperator::ArrayLengthAtLeast => "array_length_at_least",
        BodyOperator::ArrayContains => "array_contains",
        BodyOperator::EqualInteger => "equal_integer",
        BodyOperator::MapHasKey => "map_has_key",
        BodyOperator::MapDoesNotHaveKey => "map_does_not_have_key",
        BodyOperator::StructuralContains => "structural_contains",
    }
    .to_owned()
}

fn build_url_path_view(cfg: Option<&UrlPathConfig>) -> Option<UrlPathView> {
    let cfg = cfg?;
    let (value, op) = match cfg {
        UrlPathConfig::Simple(s) => (s.clone(), op_name(&RuleOp::default())),
        UrlPathConfig::Detailed(detail) => {
            let op = detail
                .op
                .as_ref()
                .map(op_name)
                .unwrap_or_else(|| op_name(&RuleOp::default()));
            (detail.value.clone(), op)
        }
    };
    Some(UrlPathView { value, op })
}

/// TOML-form name for a `RuleOp`. The `Display` impl on `RuleOp`
/// produces a human-readable form (`" == "`, `" starts with "`),
/// which is good for log output but not for a stable identifier the
/// GUI can match against. We translate to the same `snake_case` form
/// `serde(rename_all = "snake_case")` produces on the way in, so the
/// view round-trips back to the original TOML keyword.
pub fn op_name(op: &RuleOp) -> String {
    match op {
        RuleOp::Equal => "equal",
        RuleOp::NotEqual => "not_equal",
        RuleOp::StartsWith => "starts_with",
        RuleOp::NotStartsWith => "not_starts_with",
        RuleOp::EndsWith => "ends_with",
        RuleOp::NotEndsWith => "not_ends_with",
        RuleOp::Contains => "contains",
        RuleOp::NotContains => "not_contains",
        RuleOp::WildCard => "wild_card",
        RuleOp::Regex => "regex",
        RuleOp::NotRegex => "not_regex",
    }
    .to_owned()
}

fn http_method_name(m: &HttpMethod) -> String {
    m.as_str().to_owned()
}

pub fn build_respond_view(respond: &Respond) -> RespondView {
    if let Some(path) = respond.file_path.as_ref() {
        return RespondView::File {
            path: path.clone(),
            csv_records_key: respond.csv_records_key.clone(),
        };
    }
    if let Some(text) = respond.text.as_ref() {
        return RespondView::Text {
            text: text.clone(),
            status: respond.status,
        };
    }
    if let Some(status) = respond.status {
        return RespondView::Status { code: status };
    }
    // Fallback for an empty respond — not legal per validation, but
    // surface it as an empty text body so the snapshot stays
    // well-formed for GUIs that re-render mid-edit.
    RespondView::Text {
        text: String::new(),
        status: None,
    }
}

// -------------------------------------------------------------------
// File tree (depth-1 eager) — RFC 005 filtering
// -------------------------------------------------------------------

/// Built-in directory names to exclude from `FileTreeView` by default.
/// These are overwhelmingly build outputs / VCS metadata across common
/// ecosystems; projects with unusual layouts can disable via
/// `FileTreeFilter::builtin_excludes = false`.
pub const BUILTIN_EXCLUDES: &[&str] = &[
    "target",
    "node_modules",
    "dist",
    "build",
    "out",
    "__pycache__",
    ".venv",
    "vendor",
    ".cargo",
    ".gradle",
    ".idea",
    ".vscode",
];

/// Filter options controlling which entries appear in [`FileTreeView`].
///
/// # Defaults
///
/// - `show_hidden = false` — hide dotfiles / dot-directories.
/// - `builtin_excludes = true` — hide known build-output directories.
/// - `extra_excludes = []` — no additional exclusions.
/// - `include = []` — include everything (no inclusion filter).
/// - `respect_gitignore = false` — do not parse `.gitignore` files.
///
/// The defaults are intentionally conservative: they hide the noise
/// without requiring any configuration for the common case.
#[derive(Clone, Debug)]
pub struct FileTreeFilter {
    /// When `false`, entries whose name starts with `.` are excluded.
    pub show_hidden: bool,
    /// When `true`, entries whose name appears in [`BUILTIN_EXCLUDES`]
    /// are excluded.
    pub builtin_excludes: bool,
    /// Glob patterns for additional exclusions (RFC 019).
    ///
    /// Each entry is a `globset` glob pattern matched against the entry's
    /// `file_name()` component only (not the full path). A trailing `/`
    /// restricts the pattern to directories.
    ///
    /// **Breaking change from pre-5.11:** Previously these were exact-name
    /// matches. Now they are glob patterns. Literal names continue to work
    /// because a bare name with no metacharacters is a valid glob.
    pub extra_excludes: Vec<String>,
    /// If non-empty, only files whose name matches at least one pattern
    /// (glob) are included. Directories are always kept so the user can
    /// drill into them.
    pub include: Vec<String>,
    /// When `true`, parse `.gitignore` files at the directory being listed
    /// and in its ancestors (up to the nearest `.git` directory), applying
    /// the same ignore rules Git would (RFC 019). Off by default.
    pub respect_gitignore: bool,
}

impl Default for FileTreeFilter {
    fn default() -> Self {
        Self {
            show_hidden: false,
            builtin_excludes: true,
            extra_excludes: Vec::new(),
            include: Vec::new(),
            respect_gitignore: false,
        }
    }
}

impl FileTreeFilter {
    /// Return `true` iff `name` should be kept (not filtered out).
    ///
    /// `path` is the full path to the entry (used for gitignore matching).
    fn keep(
        &self,
        name: &str,
        is_dir: bool,
        path: &Path,
        gitignore: Option<&ignore::gitignore::Gitignore>,
    ) -> bool {
        // Dotfile filter
        if !self.show_hidden && name.starts_with('.') {
            return false;
        }
        // Built-in exclude list
        if self.builtin_excludes && BUILTIN_EXCLUDES.contains(&name) {
            return false;
        }
        // Extra excludes (glob patterns, RFC 019)
        if !self.extra_excludes.is_empty() {
            let mut builder = globset::GlobSetBuilder::new();
            for pat in &self.extra_excludes {
                let full_pat = if is_dir && !pat.ends_with('/') {
                    // A directory-only trailing-slash convention is handled
                    // by matching dir names with or without the slash.
                    pat.clone()
                } else {
                    pat.trim_end_matches('/').to_owned()
                };
                if let Ok(g) = globset::Glob::new(&full_pat) {
                    builder.add(g);
                }
            }
            if let Ok(set) = builder.build()
                && set.is_match(name)
            {
                return false;
            }
        }
        // .gitignore filter (RFC 019)
        if let Some(gi) = gitignore {
            let match_result = gi.matched(path, is_dir);
            if match_result.is_ignore() {
                return false;
            }
        }
        // Include filter applies only to files; directories always pass.
        if !is_dir && !self.include.is_empty() {
            let mut builder = globset::GlobSetBuilder::new();
            for pat in &self.include {
                if let Ok(g) = globset::Glob::new(pat) {
                    builder.add(g);
                }
            }
            if let Ok(set) = builder.build()
                && !set.is_match(name)
            {
                return false;
            }
        }
        true
    }
}

/// Build a `.gitignore`-aware ignore matcher for `dir` and its ancestors.
///
/// Walks up from `dir` to the filesystem root (stopping at a `.git`
/// directory if one is found) and adds any `.gitignore` files encountered.
/// Returns `None` if no `.gitignore` files were found or if parsing fails.
fn build_gitignore_for(dir: &Path) -> Option<ignore::gitignore::Gitignore> {
    let mut builder = ignore::gitignore::GitignoreBuilder::new(dir);
    let mut added = false;
    for ancestor in dir.ancestors() {
        let candidate = ancestor.join(".gitignore");
        if candidate.is_file() {
            builder.add(&candidate);
            added = true;
        }
        if ancestor.join(".git").is_dir() {
            break;
        }
    }
    if added { builder.build().ok() } else { None }
}

/// Build a depth-1 file-tree view rooted at `root`.
///
/// Applies [`FileTreeFilter::default()`] to exclude hidden entries and
/// known build-output directories. Use [`build_file_tree_with`] to
/// supply custom filter options.
pub fn build_file_tree(root: &Path) -> Option<FileTreeView> {
    build_file_tree_with(root, &FileTreeFilter::default())
}

/// Build a depth-1 file-tree view with an explicit [`FileTreeFilter`].
///
/// Returns `None` if the directory doesn't exist or can't be read.
/// Subdirectories carry `children = Some(Vec::new())` to flag them as
/// expandable-but-not-yet-expanded.
pub fn build_file_tree_with(root: &Path, filter: &FileTreeFilter) -> Option<FileTreeView> {
    let entries = std::fs::read_dir(root).ok()?;
    let mut nodes: Vec<FileNodeView> = Vec::new();

    // Build gitignore matcher once for the root directory (RFC 019).
    let gitignore = if filter.respect_gitignore {
        build_gitignore_for(root)
    } else {
        None
    };

    for entry in entries.flatten() {
        let path = entry.path();
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        let metadata = match entry.metadata() {
            Ok(m) => m,
            Err(_) => continue,
        };
        let is_dir = metadata.is_dir();
        let kind = if is_dir {
            FileNodeKind::Directory
        } else {
            FileNodeKind::File
        };

        // Apply filter — root itself is never filtered, only its contents.
        if !filter.keep(&name, is_dir, &path, gitignore.as_ref()) {
            continue;
        }

        let route_hint = if matches!(kind, FileNodeKind::File) {
            path.file_stem()
                .map(|s| format!("/{}", s.to_string_lossy()))
        } else {
            None
        };

        let children = match kind {
            FileNodeKind::Directory => Some(Vec::new()),
            FileNodeKind::File => None,
        };

        nodes.push(FileNodeView {
            name,
            path: path.to_string_lossy().into_owned(),
            kind,
            route_hint,
            children,
        });
    }

    // Stable rendering: directories first, then files; alphabetical within each group.
    nodes.sort_by(|a, b| match (&a.kind, &b.kind) {
        (FileNodeKind::Directory, FileNodeKind::File) => std::cmp::Ordering::Less,
        (FileNodeKind::File, FileNodeKind::Directory) => std::cmp::Ordering::Greater,
        _ => a.name.cmp(&b.name),
    });

    Some(FileTreeView {
        root_path: root.to_string_lossy().into_owned(),
        entries: nodes,
    })
}

/// Same shape as `build_file_tree`, but for ad-hoc subdirectory
/// expansion. Applies [`FileTreeFilter::default()`].
pub fn list_directory(path: &Path) -> Vec<FileNodeView> {
    list_directory_with(path, &FileTreeFilter::default())
}

/// Subdirectory expansion with an explicit filter.
pub fn list_directory_with(path: &Path, filter: &FileTreeFilter) -> Vec<FileNodeView> {
    build_file_tree_with(path, filter)
        .map(|t| t.entries)
        .unwrap_or_default()
}

// -------------------------------------------------------------------
// Script routes
// -------------------------------------------------------------------

/// Build a `ScriptRouteView` from a middleware path and its index in
/// `service.middlewares_file_paths`.
pub fn build_script_route_view(index: usize, source_file: &str) -> ScriptRouteView {
    let display_name = Path::new(source_file)
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| source_file.to_owned());

    ScriptRouteView {
        index,
        source_file: source_file.to_owned(),
        display_name,
    }
}