fire_scope/
output_common.rs

1use ipnet::IpNet;
2use std::{
3    collections::BTreeSet,
4    fs::{self, OpenOptions},
5    io::Write,
6    path::Path,
7};
8
9/// 汎用ヘッダー生成:国コード・AS番号などを埋め込む用途
10pub fn make_header(now_str: &str, country_code: &str, as_number: &str) -> String {
11    format!(
12        "# Generated at: {}\n# Country Code: {}\n# AS Number: {}\n\n",
13        now_str, country_code, as_number
14    )
15}
16
17/// TXT出力用の共通ヘルパー
18pub fn write_list_txt<P: AsRef<Path>>(
19    path: P,
20    ipnets: &BTreeSet<IpNet>,
21    mode: &str,
22    header: &str,
23) -> std::io::Result<()> {
24    let body = ipnets
25        .iter()
26        .map(|net| net.to_string())
27        .collect::<Vec<_>>()
28        .join("\n");
29
30    let content = format!("{}{}\n", header, body);
31
32    match mode {
33        "append" => {
34            let mut file = OpenOptions::new().create(true).append(true).open(&path)?;
35            file.write_all(content.as_bytes())?;
36        }
37        _ => {
38            fs::write(&path, &content)?;
39        }
40    }
41
42    Ok(())
43}
44
45/// NFT 出力用の共通ヘルパー
46pub fn write_list_nft<P: AsRef<Path>>(
47    path: P,
48    ipnets: &BTreeSet<IpNet>,
49    mode: &str,
50    header: &str,
51) -> std::io::Result<()> {
52    let file_path = path.as_ref();
53    let define_name = file_path
54        .file_stem()
55        .and_then(|os| os.to_str())
56        .unwrap_or("unknown_define");
57
58    let mut content = String::new();
59    content.push_str(header);
60    content.push_str(&format!("define {} {{\n", define_name));
61    for net in ipnets {
62        content.push_str(&format!("    {},\n", net));
63    }
64    content.push_str("}\n");
65
66    match mode {
67        "append" => {
68            let mut file = OpenOptions::new()
69                .create(true)
70                .append(true)
71                .open(file_path)?;
72            file.write_all(content.as_bytes())?;
73        }
74        _ => {
75            fs::write(file_path, &content)?;
76        }
77    }
78
79    Ok(())
80}