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