2024-04-09 10:42:06 +00:00
from datetime import datetime
2024-04-09 10:55:35 +00:00
from pathlib import Path
import json
import logging
2024-04-09 10:42:06 +00:00
2024-04-19 12:43:09 +00:00
from . shared import DEBUG , DEBUG_LOGGING , DEBUG_DUMP , DEBUG_TRACE , DEBUG_OBJECT_TRACE , DEBUG_OBJECT_TRACE_CALLSTACK
2023-06-20 14:40:34 +00:00
from . config import config , read_config , write_config
2024-01-29 08:24:47 +00:00
from . enums . colors import BColors
2024-04-09 10:55:35 +00:00
from . path_manager import LOCATIONS
2024-01-29 08:24:47 +00:00
"""
2024-04-09 10:55:35 +00:00
IO functions
2024-01-29 08:24:47 +00:00
"""
def _apply_color ( msg : str , color : BColors ) - > str :
if color is BColors . ENDC :
return msg
return color . value + msg + BColors . ENDC . value
def output ( msg : str , color : BColors = BColors . ENDC ) :
print ( _apply_color ( msg , color ) )
def user_input ( msg : str , color : BColors = BColors . ENDC ) :
return input ( _apply_color ( msg , color ) ) . strip ( )
2024-04-09 10:42:06 +00:00
2024-04-09 10:55:35 +00:00
def dump_to_file ( file_name : str , payload : str , is_json : bool = False , exit_after_dump : bool = False ) :
2024-04-10 07:28:28 +00:00
if not DEBUG_DUMP :
2024-04-09 10:55:35 +00:00
return
path = Path ( LOCATIONS . TEMP_DIRECTORY , file_name )
logging . warning ( f " dumping { file_name } to: \" { path } \" " )
2024-04-10 07:28:28 +00:00
if is_json and isinstance ( payload , str ) :
payload = json . loads ( payload )
2024-04-09 10:55:35 +00:00
if isinstance ( payload , dict ) :
payload = json . dumps ( payload , indent = 4 )
with path . open ( " w " ) as f :
f . write ( payload )
if exit_after_dump :
exit ( )
2024-04-10 08:25:05 +00:00
def trace ( msg : str ) :
2024-04-10 12:18:19 +00:00
if not DEBUG_TRACE :
return
2024-04-10 08:25:05 +00:00
output ( " trace: " + msg , BColors . OKBLUE )
2024-04-16 11:23:20 +00:00
def object_trace ( obj ) :
2024-04-16 11:28:16 +00:00
if not DEBUG_OBJECT_TRACE :
2024-04-16 11:23:20 +00:00
return
2024-04-19 12:43:09 +00:00
appendix = f " called by [ { ' | ' . join ( f ' { s . function } { Path ( s . filename ) . name } : { str ( s . lineno ) } ' for s in inspect . stack ( ) [ 1 : 5 ] ) } ] " if DEBUG_OBJECT_TRACE_CALLSTACK else " "
output ( " object: " + str ( obj ) + appendix , BColors . GREY )
2024-04-16 11:23:20 +00:00
2024-04-09 10:55:35 +00:00
"""
misc functions
"""
2024-04-09 10:42:06 +00:00
def get_current_millis ( ) - > int :
dt = datetime . now ( )
return int ( dt . microsecond / 1_000 )
2024-04-10 09:20:49 +00:00
def get_unix_time ( ) - > int :
return int ( datetime . now ( ) . timestamp ( ) )