Mod-Compat-Scripts/src/util/file.py
2021-08-28 23:10:30 -05:00

104 lines
3.3 KiB
Python

"""
Author: Jose Stovall | github.com/oitsjustjose | oitsjustjose.com
A script for extracting slabs (via BlockTag) from a CSV table of all blocks.
@link{https://www.curseforge.com/minecraft/mc-mods/craftdumper}
Table to be generated by CraftDumper
Script Arguments:
[python.exe] extract_slabs.py <PATH_TO_ALL_BLOCKS.CSV>
"""
import os
import sys
from typing import List, Tuple
import pandas as pd
class FORE:
"""A base colors class for printing colors to the shell"""
HEADER = "\033[95m"
BLUE = "\033[94m"
CYAN = "\033[96m"
GREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def __try_find_path() -> Tuple[List[str], str]:
"""
Makes an attempt at automagically finding the blocks csv
in the local directory if you just dropped it in and ran
this without reading up on these docstrings or anything 😠
"""
if len(sys.argv) == 2:
return sys.argv[1]
candidates: List[str] = []
for dirpath, _, filenames in os.walk("./"):
for f_name in filenames:
if f_name.endswith(".csv"):
candidates.append(f"{dirpath}/{f_name}")
for f_name in candidates:
str_data: str
with open(f_name, "r") as file:
str_data = file.readline()
if "ID" in str_data and "Tags" in str_data:
return candidates, f_name
return candidates, ""
def __try_get_blocks() -> Tuple[List[str], List[str]]:
"""
Attempts to fetch the blocks CSV as a Pandas Df object
If it cannot find or parse the file at the path given
(or the path is not given), None is returned to throw
an error later down the call stack :)
"""
print(f"{FORE.HEADER}Beginning Extract...{FORE.ENDC}")
attempts, f_name = __try_find_path()
if f_name:
print(f"Detected CSV file {f_name}")
else:
print(f"{FORE.FAIL}Error in program execution:{FORE.ENDC}")
print(f"\tpython3 {' '.join(sys.argv)} {FORE.FAIL}does not match{FORE.ENDC}")
print("\tpython3 extract_slabs.py <PATH_TO_ALL_BLOCKS.CSV>")
if attempts:
print("")
print(
f"{FORE.BOLD}Also tried the following CSVs but were missing attributes:"
)
print("\n ".join(attempts))
sys.exit(0)
d_blocks: pd.DataFrame = pd.read_csv(f_name)
d_slabs: pd.DataFrame = d_blocks.copy()
d_slabs: pd.DataFrame = d_slabs[d_slabs["Tags"].notna()]
d_slabs: pd.DataFrame = d_slabs[d_slabs["Tags"].str.contains("slab")]
d_slabs: pd.DataFrame = d_slabs[~d_slabs["Tags"].str.contains("vertical")]
# WARN: Instance of 'TextFileReader' has no 'ID' member
# IGNORE this warning - I think Pandas.DataFrame.Id is confusing it.
return d_blocks.ID.unique(), d_slabs.ID.unique()
def create_requisite_files() -> None:
"""The main runfunc for the program 😀"""
all_blocks, slabs = __try_get_blocks()
print(f"{FORE.CYAN}Writing {len(all_blocks)} blocks to ./all_blocks.txt{FORE.ENDC}")
print(f"{FORE.CYAN}Writing {len(slabs)} slabs to ./slabs.txt{FORE.ENDC}")
with open("./all_blocks.txt", "w") as file:
file.write("\n".join(all_blocks))
with open("./slabs.txt", "w") as file:
file.write("\n".join(slabs))
if __name__ == "__main__":
create_requisite_files()