Skip to content
Snippets Groups Projects
generatersenum.py 2.12 KiB
import csv


def generate_rust_enum(csv_file):
    rust_enum = "use phf::phf_map;\n\nenum Mime {\n"

    with open(csv_file, "r") as file:
        csv_data = csv.reader(file)
        next(csv_data)  # Skip the header row

        for row in csv_data:
            if row[1] == "":
                continue
            if "DEPRECATED" in row[0]:
                continue
            name = format_enum_member(row[0:2])
            rust_enum += f"\t{name},\n"

    rust_enum += "}\n\n"
    rust_enum += "impl std::fmt::Display for Mime {\n"
    rust_enum += "\tfn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n"
    rust_enum += "\t\tmatch self {\n"

    with open(csv_file, "r") as file:
        csv_data = csv.reader(file)
        next(csv_data)  # Skip the header row
        for row in csv_data:
            if row[1] == "":
                continue
            if "DEPRECATED" in row[0]:
                continue
            name = format_enum_member(row[0:2])
            rust_enum += f'\t\t\tMime::{name} => write!(f, "{row[1]}"),\n'

    rust_enum += "\t\t}\n\t}\n}\n\n"

    rust_enum += "static MimeMap: phf::Map<&'static str, Mime> = phf_map! {\n"
    with open(csv_file, "r") as file:
        csv_data = csv.reader(file)
        next(csv_data)
        for row in csv_data:
            if row[1] == "":
                continue
            if "DEPRECATED" in row[0]:
                continue
            key = row[1]
            value = format_enum_member(row[0:2])
            rust_enum += f'\t"{key}" => Mime::{value},\n'
    rust_enum += "};"

    return rust_enum


def format_enum_member(name):
    prefix = "".join(name[1].split("/")[0:-1])
    name = name[0].split("-")
    words = []
    parts = []
    for part in name:
        parts += part.split("+")
    for part in parts:
        words += part.split(".")

    formatted_name = "".join(word.capitalize() for word in words)
    if not formatted_name.startswith(prefix.capitalize()):
        formatted_name = prefix.capitalize() + formatted_name
    return formatted_name


# Usage example
csv_file = "mimes.csv"
rust_enum_code = generate_rust_enum(csv_file)
print(rust_enum_code)