finch-filer/src/finch_filer/utils.py
2025-11-22 14:56:29 -08:00

106 lines
No EOL
3.3 KiB
Python

"""Utility functions."""
__author__ = "Gull"
import os
import sys
import time
import json
import pathlib
import appdirs as ad
KILOBYTES = 1024
def format_bytes(bytes):
"""Returns a B, KB, MB, GB, or TB string from the given bytes."""
units = {
"B": float(1),
"KB": float(KILOBYTES),
"MB": float(KILOBYTES ** 2), # 1,048,576
"GB": float(KILOBYTES ** 3), # 1,073,741,824
"TB": float(KILOBYTES ** 4) # 1,099,511,627,776
}
if bytes < units["KB"]:
return f"{bytes} B"
elif units["KB"] <= bytes < units["MB"]:
return f"{(bytes / units['KB']):.2f} KB"
elif units["MB"] <= bytes < units["GB"]:
return f"{(bytes / units['MB']):.2f} MB"
elif units["GB"] <= bytes < units["TB"]:
return f"{(bytes / units['GB']):.2f} GB"
elif units["TB"] <= bytes:
return f"{(bytes / units['TB']):.2f} TB"
def format_date(timestamp):
"""Returns a time string (ISO 8601) from the given integer timestamp."""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
def load_json_file(filepath):
"""Opens a JSON file, and returns JSON data as a dict."""
try:
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
return data
except Exception as error:
raise error
def save_json_file(filepath, data, raw=False):
"""Saves a JSON file, given a dict."""
try:
with open(filepath, "w", encoding="utf-8") as f:
json.dump(data, f, sort_keys=True, indent=None if raw else 2)
except Exception as error:
raise error
def get_icon_file():
"""Attempts to return a valid icon file."""
if os.name == "nt":
path = ""
try:
path = sys._MEIPASS # For PyInstaller
except Exception:
path = os.path.dirname(os.path.abspath(__file__))
return pathlib.Path(path).parent.parent / "icon.ico"
else:
path = os.path.dirname(os.path.abspath(__file__))
return pathlib.Path(path).parent.parent / "icon.svg"
def parse_dir(path="", ignore_mkdir=False):
"""Converts and creates a directory (can be full file path)."""
if path[0] == "~": # Denotes the current user directory
path = pathlib.Path(path).expanduser()
elif path[0] == "%": # Denotes the local appdata directory
path = pathlib.Path(ad.user_data_dir(None, False)) / path.lstrip("%/")
elif path[0] == "#": # Denotes the project root directory
try:
base_path = sys._MEIPASS # For PyInstaller
except Exception:
base_path = os.path.dirname(os.path.abspath(__file__))
path = pathlib.Path(base_path).parent.parent / path.lstrip("#/")
else:
path = pathlib.Path(path)
if not ignore_mkdir:
try:
# This seems sloppy
dir = str(path)
_, ext = os.path.splitext(dir)
if len(ext) > 0: dir = os.path.dirname(dir) #Is file
pathlib.Path(dir).mkdir(parents=True, exist_ok=True)
except Exception as error:
raise error
# Returns as a string
return str(path)
def get_log_config(path="~/", level=None):
return {
"filename":parse_dir(path),
"filemode":"w",
"level":level,
"format":"{asctime}: [{levelname}] {message}",
"style":"{"
}