import collections
input_file = "content.txt"
output_file = "src/generated.rs"
file_template = """
use phf::phf_map;
use crate::abbreviation::{{Abbreviation, Sign}};
pub(crate) static MAX_ABBREVIATION_LEN: usize = {max_len};
pub(crate) static ABBREVIATIONS: phf::Map<&'static str, &[Abbreviation]> = phf_map! {{
{content}
}};
"""
init_template = """Abbreviation::new("{abbr}", "{name}", {sign}, {hour_offset}, {minute_offset})"""
join_template = """ "{abbr}" => &[{collected}],"""
def write_items(abbreviation, entries):
collected = []
for name, sign, hour_offset, minute_offset in entries:
tp_sign = "Sign::Plus" if sign == "+" else "Sign::Minus"
collected.append(init_template.format(
abbr=abbreviation.upper(), name=name, sign=tp_sign, hour_offset=hour_offset, minute_offset=minute_offset))
joined = ", ".join(collected)
tp_init = join_template.format(abbr=abbreviation.upper(), collected=joined)
return tp_init
with open(output_file, "w") as output_fp:
abbr_entries = []
max_abbr_length = 0
with open(input_file) as input_fp:
entries = collections.OrderedDict()
for line in input_fp.readlines():
line = line.strip()
if len(line) == 0 or line[0] == "#":
continue
components = line.split("\t")
if len(components) != 3:
print("Invalid line:", line)
break
abbreviation = components[0].lower()
if abbreviation == "dst":
continue
name = components[1].lower()
timezone = components[2]
items = timezone.replace("UTC", "").strip().split(" ")
if len(items) != 2 or not items[0] in ["+", "-"]:
print("Invalid timezone info:", timezone, name)
break
sign = items[0]
hour_offset = 0
minute_offset = 0
if items[1].find(":") != -1:
c = items[1].split(":")
if len(c) != 2:
print("Invalid timezone time:", items[1], name)
break
hour_offset = int(c[0])
minute_offset = int(c[1])
else:
hour_offset = int(items[1])
if len(abbreviation) > max_abbr_length:
max_abbr_length = len(abbreviation)
if not abbreviation in entries:
entries[abbreviation] = [
(name, sign, hour_offset, minute_offset)]
else:
entries[abbreviation].append(
(name, sign, hour_offset, minute_offset))
for key in entries:
abbr_entries.append(write_items(key, entries[key]))
content = "\n".join(abbr_entries)
output_fp.write(file_template.format(
content=content, max_len=max_abbr_length))