cargo_manifest_proc_macros/syn_utils.rs
1use proc_macro2::Span;
2use syn::token::PathSep;
3
4/// Converts a crate name to a global [`syn::Path`].
5/// It transforms '-' to '_' and adds a leading colon.
6///
7/// Note: This does not resolve the crate name to a path.
8#[must_use = "This function returns the path to the crate as a syn::Path"]
9pub fn crate_name_to_syn_path(crate_name: &str) -> syn::Path {
10 let crate_name = crate_name.replace('-', "_");
11 let mut path = syn::Path::from(syn::Ident::new(&crate_name, Span::call_site()));
12 path.leading_colon = Some(PathSep::default());
13 path
14}
15
16/// Pretty format a [`syn::Path`] as a string.
17#[must_use = "This function returns the formatted path as a string"]
18pub fn pretty_format_syn_path(path: &syn::Path) -> String {
19 let mut path_str = String::new();
20 let has_leading_colon = path.leading_colon.is_some();
21 if has_leading_colon {
22 path_str.push_str("::");
23 }
24 for segment in &path.segments {
25 path_str.push_str(&segment.ident.to_string());
26 path_str.push_str("::");
27 }
28 path_str.truncate(path_str.len() - 2);
29 path_str
30}