Skip to main content

tonneau_build/codegen/
utils.rs

1use syn::Ident;
2
3use super::prost_sanatize;
4
5pub(crate) fn field_ident_from_str(s: impl AsRef<str>) -> Ident {
6    syn::parse_str(&prost_sanatize::to_snake(s.as_ref())).unwrap()
7}
8
9pub(crate) fn type_ident_from_str(s: impl AsRef<str>) -> Ident {
10    syn::parse_str(&prost_sanatize::to_upper_camel(s.as_ref())).unwrap()
11}
12
13pub(crate) fn get_common_import_path(package: &str, end: &str) -> syn::Path {
14    let start_parts: Vec<&str> = package.split('.').collect();
15    let mut end_parts: Vec<&str> = end.split('.').collect();
16
17    let end_part =
18        type_ident_from_str(end_parts.pop().expect("end path must not be empty")).to_string();
19
20    let common_len = start_parts
21        .iter()
22        .zip(&end_parts)
23        .take_while(|(a, b)| a == b)
24        .count();
25
26    let num_supers = start_parts.len().saturating_sub(common_len);
27
28    let mut path_parts = Vec::new();
29
30    for _ in 0..num_supers {
31        path_parts.push("super".to_string());
32    }
33
34    for end_part in end_parts[common_len..].iter() {
35        path_parts.push(field_ident_from_str(end_part).to_string());
36    }
37
38    path_parts.push(end_part);
39
40    syn::parse_str(&path_parts.join("::")).expect("failed to parse path")
41}
42
43#[cfg(test)]
44#[cfg_attr(coverage_nightly, coverage(off))]
45mod tests {
46    use quote::ToTokens;
47
48    use super::*;
49
50    #[test]
51    fn test_get_common_import_path() {
52        assert_eq!(
53            get_common_import_path("a.b.c", "a.b.d")
54                .to_token_stream()
55                .to_string(),
56            syn::parse_str::<syn::Path>("super::D")
57                .unwrap()
58                .to_token_stream()
59                .to_string()
60        );
61        assert_eq!(
62            get_common_import_path("a.b.c", "a.b.c.d")
63                .to_token_stream()
64                .to_string(),
65            syn::parse_str::<syn::Path>("D")
66                .unwrap()
67                .to_token_stream()
68                .to_string()
69        );
70        assert_eq!(
71            get_common_import_path("a.b.c", "a.b.c")
72                .to_token_stream()
73                .to_string(),
74            syn::parse_str::<syn::Path>("super::C")
75                .unwrap()
76                .to_token_stream()
77                .to_string()
78        );
79        assert_eq!(
80            get_common_import_path("a.b.c", "a.b")
81                .to_token_stream()
82                .to_string(),
83            syn::parse_str::<syn::Path>("super::super::B")
84                .unwrap()
85                .to_token_stream()
86                .to_string()
87        );
88    }
89}