Skip to main content

actix_cloud_codegen/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3use proc_macro::TokenStream;
4use quote::quote;
5#[cfg(feature = "i18n")]
6use std::{collections::BTreeMap, env, path};
7
8#[cfg(feature = "i18n")]
9mod i18n;
10
11/// Attribute macro for the `main` function, equivalent to
12/// `#[actix_web::rt::main(system = "actix_cloud::actix_web::rt::System")]`.
13///
14/// ```ignore
15/// #[actix_cloud::main]
16/// async fn main() -> std::io::Result<()> {
17///     Ok(())
18/// }
19/// ```
20#[proc_macro_attribute]
21pub fn main(_: TokenStream, item: TokenStream) -> TokenStream {
22    let mut output: TokenStream = (quote! {
23        #[actix_cloud::actix_web::rt::main(system = "actix_cloud::actix_web::rt::System")]
24    })
25    .into();
26
27    output.extend(item);
28    output
29}
30
31#[cfg(feature = "i18n")]
32/// Init I18n translations.
33///
34/// This will load all translations by glob `**/*.yml` from the given path.
35///
36/// ```ignore
37/// i18n!("locales");
38/// ```
39///
40/// # Panics
41///
42/// Panics is variable `CARGO_MANIFEST_DIR` is empty.
43#[proc_macro]
44pub fn i18n(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
45    let option = match syn::parse::<i18n::Option>(input) {
46        Ok(input) => input,
47        Err(err) => return err.to_compile_error().into(),
48    };
49
50    // CARGO_MANIFEST_DIR is current build directory
51    let cargo_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is empty");
52    let current_dir = path::PathBuf::from(cargo_dir);
53    let locales_path = current_dir.join(option.locales_path);
54
55    let data = rust_i18n_support::load_locales(&locales_path.display().to_string(), |_| false);
56    let mut translation = BTreeMap::new();
57    for (lang, mp) in data {
58        for (k, v) in mp {
59            translation.insert(format!("{lang}.{k}"), v);
60        }
61    }
62    let code = i18n::generate_code(&translation);
63
64    if rust_i18n_support::is_debug() {
65        println!("{code}");
66    }
67
68    code.into()
69}