hirust-macros 0.1.18

A Rust Macros
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use crate::route_file::route_cfg;
use hirust_auth;
use proc_macro::{TokenStream, TokenTree};
use serde_json::Value;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io;
use std::io::Write;
use std::path::Path;
use zip::ZipArchive;

#[allow(dead_code)]
pub fn create_file(file_path: &str) {
    // 检查文件是否存在
    if !Path::new(file_path).exists() {
        // 文件不存在,尝试创建文件
        match std::fs::File::create(file_path) {
            Ok(_) => println!("文件创建成功:{}", file_path),
            Err(e) => println!("创建文件失败:{}", e),
        }
    }
}

#[allow(dead_code)]
pub fn create_and_append(file_path: &str, content: &str) {
    // 创建文件
    create_file(file_path);

    // 打开文件并追加内容
    match OpenOptions::new().append(true).open(file_path) {
        Ok(mut file) => {
            // 追加内容
            if let Err(e) = writeln!(file, "{}", content) {
                println!("追加内容失败:{}", e);
            }
        }
        Err(e) => println!("打开文件失败:{}", e),
    }
}

#[allow(dead_code)]
pub fn write_file(file_path: &str, content: &str) {
    match OpenOptions::new().write(true).open(file_path) {
        Ok(mut file) => {
            // 追加内容
            if let Err(e) = writeln!(file, "{}", content) {
                println!("写文件内容失败:{}", e);
            }
        }
        Err(e) => println!("打开文件失败:{}", e),
    }
}

#[allow(dead_code)]
pub fn reverse_string(s: &str) -> String {
    s.chars().rev().collect::<String>()
}

/**
let zip_path = "example.zip";
let extract_dir = "extracted_files";
*/
#[allow(dead_code)]
pub fn extract_zip(zip_path: &str, extract_to: &str) -> io::Result<()> {
    let file = File::open(zip_path)?;
    let mut archive = ZipArchive::new(file)?;

    for i in 0..archive.len() {
        let mut file_in_zip = archive.by_index(i)?;
        let outpath = match file_in_zip.enclosed_name() {
            Some(path) => {
                let mut path_buf = Path::new(extract_to).to_path_buf();
                path_buf.push(path);
                path_buf
            }
            None => continue,
        };

        if file_in_zip.is_dir() {
            std::fs::create_dir_all(&outpath)?;
        } else {
            if let Some(p) = outpath.parent() {
                if !p.exists() {
                    std::fs::create_dir_all(&p)?;
                }
            }
            let mut outfile = File::create(&outpath)?;
            io::copy(&mut file_in_zip, &mut outfile)?;
        }
    }
    Ok(())
}

#[allow(unused)]
pub fn parse_token(args: TokenStream, req_map: HashMap<String, String>) -> (String, String) {
    let auth_info = parse_attr(args);

    let path = auth_info.clone().path.clone();
    let tag = auth_info.clone().tag.clone();

    let middlewares: Vec<String> = auth_info
        .clone()
        .middleware
        .clone()
        .split(",")
        .map(|m| m.to_string().replace(" ", ""))
        .collect();

    match hirust_auth::exist(tag.clone()) {
        Some(_) => {
            panic!("This handler tag: {} is duplication", tag.clone());
        }
        None => {
            let route_cfg = route_cfg();
            if route_cfg.is_empty() {
                panic!(
                    "file: {}, line: {}, message: route config is empty, please check the route configuration path and compilation order.",
                    file!(),
                    line!()
                );
            }
            let serialized = serde_json::to_string(&auth_info.clone()).unwrap();
            create_and_append(route_cfg.as_str(), &serialized.as_str());
        }
    }

    let mut contents = String::new();
    if !middlewares.is_empty() {
        let mut req = String::new();

        if req_map.contains_key("actix_web::HttpRequest") {
            req = "&".to_owned() + &*req_map.get("actix_web::HttpRequest").unwrap().to_string();
        } else if req_map.contains_key("HttpRequest") {
            req = "&".to_owned() + &*req_map.get("HttpRequest").unwrap().to_string();
        } else if req_map.contains_key("&HttpRequest") {
            req = req_map.get("&HttpRequest").unwrap().to_string();
        } else {
            panic!(
                "There is no request parameter {} `actix_web::HttpRequest`",
                req
            );
        }

        for middleware in middlewares {
            // 调用拦截器
            let temp = format!(
                r#"
                match interceptor({}({}, {})) {{
                    Some(response) => return response.respond_to({}),
                    _ => (),
                }}
                "#,
                middleware,
                req.clone().to_string(),
                tag.clone().to_string(),
                req.clone().to_string()
            );
            contents += &temp;
        }

        contents = format!(r#"{{{}}}"#, contents);
    } else {
        contents = format!(r#"{{{}}}"#, "");
    }

    (path, contents)
}

#[allow(unused)]
pub fn parse_attr(args: TokenStream) -> hirust_auth::Auth {
    let mut is_method = false;
    let mut method = String::new();
    let mut is_path = false;
    let mut path = String::new();
    let mut is_middleware = false;
    let mut middlewares: Vec<String> = vec![];
    let mut middleware = String::new();
    let mut is_tag = false;
    let mut tag = String::new();
    let mut is_auth = false;
    let mut auth = true;
    let mut is_desc = false;
    let mut desc = String::new();
    for arg in args.into_iter() {
        //println!("{}:{} {:?}", file!(), line!(), &arg);
        if matches!(&arg, TokenTree::Ident(_)) && "method".eq(&arg.to_string()) {
            is_method = true;
        }
        if is_path && matches!(&arg, TokenTree::Literal(_)) {
            let temp = arg.to_string();
            method = temp.clone().replace("\"", "");
            is_method = false;
        }
        if matches!(&arg, TokenTree::Ident(_)) && "path".eq(&arg.to_string()) {
            is_path = true;
        }
        if is_path && matches!(&arg, TokenTree::Literal(_)) {
            let temp = arg.to_string();
            path = temp.clone().replace("\"", "");
            is_path = false;
        }
        if matches!(&arg, TokenTree::Ident(_)) && "middleware".eq(&arg.to_string()) {
            is_middleware = true;
        }
        if is_middleware && matches!(&arg, TokenTree::Group(_)) {
            middleware = arg.to_string();
            middleware = middleware
                .clone()
                .replace("{", "")
                .replace("}", "")
                .replace(" ", "");
            middlewares = middleware
                .split(",")
                .map(|m| m.to_string().replace(" ", ""))
                .collect();
            is_middleware = false;
        }
        if matches!(&arg, TokenTree::Ident(_)) && "tag".eq(&arg.to_string()) {
            is_tag = true;
        }
        if is_tag && matches!(&arg, TokenTree::Literal(_)) {
            tag = arg.clone().to_string();
            is_tag = false
        }
        if matches!(&arg, TokenTree::Ident(_)) && "auth".eq(&arg.to_string()) {
            is_auth = true;
        }
        if is_auth && !"auth".eq(&arg.to_string()) && matches!(&arg, TokenTree::Ident(_)) {
            if "false".eq(&arg.to_string()) {
                auth = false;
            }
            is_auth = false;
        }
        if matches!(&arg, TokenTree::Ident(_)) && "desc".eq(&arg.to_string()) {
            is_desc = true;
        }
        if is_desc && matches!(&arg, TokenTree::Literal(_)) {
            let temp = arg.to_string(); // rust 如何把代码块里的字符串拿到代码块外面来
            desc = temp.replace("\"", "");
            is_desc = false;
        }
    }

    hirust_auth::Auth {
        method: method.clone().replace("\"", ""),
        path: path.clone().replace("\"", ""),
        tag: tag.clone().replace("\"", ""),
        desc: desc.clone().replace("\"", ""),
        middleware: middleware.clone().replace("\"", ""),
        auth: auth.to_string(),
    }
    .clone()
}

#[allow(unused)]
pub fn parse_auth_info(args: proc_macro2::TokenStream) -> hirust_auth::Auth {
    let mut method = String::new();

    let serialized = serde_json::to_string(&hirust_auth::Auth::default())
        .expect("struct Auth serialization failed");
    //println!("{}:{} {:?}", file!(), line!(), &serialized);

    // 解析JSON字符串到Value枚举
    let json_value: Value = serde_json::from_str(&serialized).expect("JSON was not well-formatted");

    // 将Value转换为HashMap<String, Value>
    let auth_keys_map: HashMap<String, Value> =
        serde_json::from_value(json_value).expect("JSON was not well-formatted");
    let mut keys: Vec<String> = vec![];
    let mut values: Vec<String> = vec![];

    for arg in args.clone().into_iter() {
        match arg {
            // 遍历TokenTree::Group下的TokenStream
            proc_macro2::TokenTree::Group(ref group) => {
                //println!("{}:{} {:?}", file!(), line!(), &group);
                // 获取组内的TokenStream并再次遍历
                let group_tokens = group.stream();
                for inner_group in group_tokens {
                    match inner_group {
                        // ref 模式 https://rustwiki.org/zh-CN/rust-by-example/scope/borrow/ref.html
                        proc_macro2::TokenTree::Ident(ref ident) => {
                            //println!("{}:{} {:?}", file!(), line!(), &ident);
                            method = ident.clone().to_string().replace("\"", "");
                            //println!("{}:{} {:?}", file!(), line!(), &method);
                        }
                        proc_macro2::TokenTree::Group(ref group) => {
                            //println!("{}:{} {:?}", file!(), line!(), &group);
                            // 获取组内的TokenStream并再次遍历
                            let group_tokens = group.stream();
                            for inner_group in group_tokens {
                                match inner_group {
                                    proc_macro2::TokenTree::Ident(ref ident) => {
                                        //println!("{}:{} {}", file!(), line!(), &ident.to_string());
                                        if auth_keys_map.contains_key(&ident.to_string()) {
                                            keys.push(ident.to_string());
                                        } else {
                                            values.push(ident.to_string().replace("\"", ""));
                                        }
                                    }
                                    proc_macro2::TokenTree::Literal(ref literal) => {
                                        values.push(literal.to_string().replace("\"", ""));
                                    }
                                    proc_macro2::TokenTree::Group(ref group) => {
                                        // 获取组内的TokenStream并再次遍历
                                        let group_tokens = group.stream();
                                        values.push(
                                            group_tokens.to_string().replace(" ", "").to_string(),
                                        );
                                    }
                                    _ => {}
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    //println!("{}:{} {:?}", file!(), line!(), &keys);
    //println!("{}:{} {:?}", file!(), line!(), &values);

    let mut attr_map: HashMap<String, String> = HashMap::new();
    attr_map.insert("method".to_string(), method.to_string());
    for index in 0..keys.len() {
        attr_map.insert(keys[index].to_string(), values[index].to_string());
    }

    let mut auth_map: HashMap<String, String> = HashMap::new();
    for (key, value) in auth_keys_map {
        if attr_map.contains_key(key.as_str()) {
            auth_map.insert(key.clone(), attr_map.get(&key).unwrap().to_string());
        } else {
            if key.clone().eq("auth") {
                auth_map.insert(key.clone(), "true".to_string());
            } else {
                auth_map.insert(key.clone(), String::new());
            }
        }
    }

    if auth_map.get("path").unwrap().is_empty() {
        panic!("path cannot be empty.");
    }
    if auth_map.get("tag").unwrap().is_empty() {
        //panic!("tag cannot be empty.");
    }

    //println!("{}:{} {:?}", file!(), line!(), &auth_map);

    let serialized = serde_json::to_string(&auth_map).expect("attr_map serialization failed");
    //println!("{}:{} {}", file!(), line!(), &serialized);

    // 解析JSON字符串到Value枚举
    let auth_info: hirust_auth::Auth =
        serde_json::from_str(&serialized).expect("JSON was not well-formatted");
    //println!("{}:{} {:?}", file!(), line!(), &auth_info);

    auth_info.clone()
}

#[allow(unused)]
pub fn parse_group_extract_args(tokens: proc_macro2::TokenStream) -> HashMap<String, String> {
    let mut args_map = HashMap::<String, String>::new();
    for token in tokens.into_iter() {
        match token {
            // 遍历TokenTree::Group下的TokenStream
            proc_macro2::TokenTree::Group(ref group) => {
                let mut key = String::new();
                let mut value = String::new();
                let mut punctuation = String::new();
                let mut punctuation_counter = 0;

                // 获取组内的TokenStream并再次遍历
                let inner_tokens = group.stream();
                //println!("{}:{} {:?}", file!(), line!(), inner_tokens);
                for inner_tt in inner_tokens {
                    match inner_tt {
                        // ref 模式 https://rustwiki.org/zh-CN/rust-by-example/scope/borrow/ref.html
                        proc_macro2::TokenTree::Ident(ref ident) => {
                            if punctuation.is_empty() {
                                value = ident.clone().to_string();
                            } else {
                                if punctuation_counter >= 1 {
                                    key = key + &*ident.clone().to_string();
                                }
                            }
                        }
                        proc_macro2::TokenTree::Punct(ref punct) => {
                            if punct.to_string() == ":" {
                                punctuation_counter += 1;
                                punctuation = punct.clone().to_string();
                                if punctuation_counter > 1 {
                                    key = key + &*punct.clone().to_string();
                                }
                            } else if punct.to_string() == "," {
                                args_map.insert(key.clone(), value.clone());
                                key = String::new();
                                value = String::new();
                                punctuation = String::new();
                                punctuation_counter = 0;
                            } else {
                                key = key + &*punct.clone().to_string();
                            }
                        }
                        // 可以根据需要处理更多类型...
                        _ => (), // 处理其他类型或忽略
                    }
                }
                if !key.is_empty() && !value.is_empty() {
                    args_map.insert(key.clone(), value.clone());
                }
            }
            // 处理其他类型的TokenTree...
            _ => (), // 或者忽略非Group类型的TokenTree
        }
    }
    //println!("{}:{} {:?}", file!(), line!(), args_map);
    args_map
}

#[allow(unused)]
pub fn parse_group_extract_scope(tokens: proc_macro2::TokenStream) -> HashMap<String, String> {
    let mut args_map = HashMap::<String, String>::new();
    for token in tokens.into_iter() {
        match token {
            // 遍历TokenTree::Group下的TokenStream
            proc_macro2::TokenTree::Group(ref group) => {
                let mut key = String::new();
                let mut value = String::new();
                let mut punctuation = String::new();
                let mut punctuation_counter = 0;

                // 获取组内的TokenStream并再次遍历
                let inner_tokens = group.stream();
                for inner_tt in inner_tokens {
                    match inner_tt {
                        // ref 模式 https://rustwiki.org/zh-CN/rust-by-example/scope/borrow/ref.html
                        proc_macro2::TokenTree::Ident(ref ident) => {
                            if punctuation.is_empty() {
                                value = ident.clone().to_string();
                            } else {
                                if punctuation_counter >= 1 {
                                    key = key + &*ident.clone().to_string();
                                }
                            }
                        }
                        proc_macro2::TokenTree::Punct(ref punct) => {
                            if punct.to_string() == ":" {
                                punctuation_counter += 1;
                                punctuation = punct.clone().to_string();
                                if punctuation_counter > 1 {
                                    key = key + &*punct.clone().to_string();
                                }
                            } else if punct.to_string() == "," {
                                args_map.insert(key.clone(), value.clone());
                                key = String::new();
                                value = String::new();
                                punctuation = String::new();
                                punctuation_counter = 0;
                            } else {
                                key = key + &*punct.clone().to_string();
                            }
                        }
                        // 可以根据需要处理更多类型...
                        _ => (), // 处理其他类型或忽略
                    }
                }
                if !key.is_empty() && !value.is_empty() {
                    args_map.insert(key.clone(), value.clone());
                }
            }
            // 处理其他类型的TokenTree...
            _ => (), // 或者忽略非Group类型的TokenTree
        }
    }
    args_map
}