Skip to main content

switchback_traits/
paths.rs

1//! Format-agnostic path helpers for entity output layout.
2
3/// Relative output directory segment for a stored entity category slug.
4pub fn entity_category_dir(category: &str) -> &str {
5    match category {
6        "schema" => "schemas",
7        "operation" => "operations",
8        "parameter" => "parameters",
9        "response" => "responses",
10        "request-body" => "request-bodies",
11        "security-scheme" => "security-schemes",
12        "service" => "services",
13        other => other,
14    }
15}
16
17/// Relative output path for an entity page under a group's markdown tree.
18///
19/// Shape: `{group_dir}/{category_dir}/{name}.md` using forward slashes.
20/// Does not include [`Options::markdown_root`](crate::Options::markdown_root).
21///
22/// Full slug parity with protobuf-mdbook is deferred; this strips path
23/// separators from `name` only.
24pub fn entity_rel_path(group_dir: &str, category_dir: &str, name: &str) -> String {
25    let group = group_dir.trim_matches('/');
26    let category = category_dir.trim_matches('/');
27    let safe_name = sanitize_entity_name(name);
28    if group.is_empty() {
29        format!("{category}/{safe_name}.md")
30    } else {
31        format!("{group}/{category}/{safe_name}.md")
32    }
33}
34
35fn sanitize_entity_name(name: &str) -> String {
36    name.replace(['/', '\\'], "-")
37}
38
39#[cfg(test)]
40mod tests {
41    use super::entity_rel_path;
42
43    #[test]
44    fn empty_group_dir() {
45        assert_eq!(entity_rel_path("", "schemas", "Pet"), "schemas/Pet.md");
46    }
47
48    #[test]
49    fn nested_group_dir() {
50        assert_eq!(
51            entity_rel_path("v1/pets", "operations", "listPets"),
52            "v1/pets/operations/listPets.md"
53        );
54    }
55
56    #[test]
57    fn hyphenated_category_dir() {
58        assert_eq!(
59            entity_rel_path("default", "request-bodies", "CreatePet"),
60            "default/request-bodies/CreatePet.md"
61        );
62    }
63
64    #[test]
65    fn strips_path_separators_in_name() {
66        assert_eq!(
67            entity_rel_path("g", "schemas", "foo/bar"),
68            "g/schemas/foo-bar.md"
69        );
70    }
71}