-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
executable file
·2909 lines (2312 loc) · 86.2 KB
/
utils.py
File metadata and controls
executable file
·2909 lines (2312 loc) · 86.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import argparse
import ast
import boto3
import calendar
import colorama
import csv
import datetime
import inspect
import json
import lorem
import math
import operator
import os
import platform
import random
import socket
import sys
import textwrap
import typing
import tomllib
import uuid
import yaml
from colorama import init as colorama_init
from colorama import Fore
from colorama import Style
from datetime import date, datetime, timezone, timedelta
from inspect import getframeinfo, stack
from io import StringIO
from rich.console import Console
from typing import Any, List, TypeVar, Tuple, get_type_hints
from yaml.loader import SafeLoader, FullLoader, Loader, BaseLoader
# Initilize
console = Console()
colorama_init()
if platform.system() == 'Windows':
from colorama import just_fix_windows_console
just_fix_windows_console()
# Config
def get_config_file():
"""Returns content of ./cocnfig.toml file if exist"""
if 'CFG_UTILS' in globals():
return globals()['CFG_UTILS']
res = {}
path = cur_dir()['Path']
# look for cfg in possible paths
cfg_paths = [
'', # current path
'..', # one path above
'../cfg',
'../..'
'../../cfg'
]
for cfg_path in cfg_paths:
config = f'{path}/{cfg_path}/config.toml'
if os.path.isfile(config):
with open(config, "rb") as f:
res = tomllib.load(f)
globals()['CFG_UTILS'] = res
return res
def get_config(string: str | None = None):
"""Returns config file or config key
Args:
key (str): config key, default None
Retunrs:
if key is None returns config map dict of {key: value, ...}
if key is not None return in below order:
1. global varibale
2. value of key in env vars
3. value of key in config file
4. default as defined in cMap[key]
"""
CFG_UTILS = get_config_file()
cMap = {
'CACHE_PATH': None,
'LOG_CALLER': None,
'LOG_DT': None,
'LOG_DT_FMT': '%d-%b-%Y %H:%M:%S',
'LOGLEVEL': 'WARNING',
'LOG_META_COLOR': 'iGray',
'UTC': None,
'COLORED': True,
'INDENT': 4,
'IND_SPC': ' ' * 4,
'LEAD': 3,
'REP': '=',
'WIDTH': 90,
'UNITTEST': None,
}
globals_var = globals()
res = {}
# config order is global, env var, config file & default or None
for key in cMap.keys():
# ex: 'INDENT': os.environ.get('INDENT', CFG_UTILS.get('INDENT', 4),
res[key] = os.environ.get(key, CFG_UTILS.get(key, cMap[key]))
# env var should be converted to int
if isinstance(cMap[key], int):
res[key] = int(res[key])
if key in globals_var:
res[key] = globals_var[key]
res['IND_SPC'] = ' ' * res['INDENT'] # depends on ['INDENT']
return res if string is None else res.get(string, '')
# Log Management
def cur_log():
"""Returns current log level"""
CFG_UTILS = get_config_file()
if 'LOGLEVEL' in globals():
return globals()['LOGLEVEL']
else:
return os.environ.get('LOGLEVEL', CFG_UTILS.get('LOGLEVEL', 'WARNING')).upper()
def isLog(level: str) -> bool | None:
"""Returns True, Flase or None (invalid level) for given level"""
LOGLEVEL = cur_log()
level = level.lower()
levels = {
'trace': LOGLEVEL in [ 'TRACE' ],
'debug': LOGLEVEL in [ 'TRACE', 'DEBUG' ],
'info': LOGLEVEL in [ 'TRACE', 'DEBUG', 'INFO' ],
'success': LOGLEVEL in [ 'TRACE', 'DEBUG', 'INFO', 'SUCCESS', ],
'warning': LOGLEVEL in [ 'TRACE', 'DEBUG', 'INFO', 'SUCCESS', 'WARN', 'WARNING' ],
'error': LOGLEVEL in [ 'TRACE', 'DEBUG', 'INFO', 'SUCCESS', 'WARN', 'WARNING', 'ERROR' ],
'critical': LOGLEVEL in [ 'TRACE', 'DEBUG', 'INFO', 'SUCCESS', 'WARN', 'WARNING', 'ERROR', 'CRITICAL' ],
}
return levels.get(level)
def log_levels():
"""Returns list of log levels"""
return [
'TRACE',
'DEBUG',
'INFO',
'WARNING',
'ERROR',
'CRITICAL',
]
def log_functions():
"""Returns list of log logging functions"""
return [
'trace',
'debug',
'info',
'success',
'warning',
'error',
'abort',
'sysExit',
]
def log_fmt(caller: object):
"""Returns string from caller object of <class 'inspect.Traceback'>
Args:
caller (object): should be getframeinfo(stack()[1][0])
Returns (str):
[datetime :: ] [File caller.filename :: ] L#{caller.lineno} ::
"""
res = ''
if get_config('LOG_DT'):
res += f' {get_dt_log()} :: '
if get_config('LOG_CALLER'):
res += f'File {caller.filename} :: ' # type: ignore
res += f'L#{caller.lineno} ::' # type: ignore
if get_config('LOG_META_COLOR'):
res = iColor(res, get_config('LOG_META_COLOR'))
return res
def print_stderr(*args, **kwargs):
"""Prints to sys.stderr. Use it like print()"""
print(*args, file=sys.stderr, **kwargs)
def trace(*args, **kwargs):
"""Prints csv TRACE log to sys.stderr. Use it like print()"""
if not isTrace():
return
caller = getframeinfo(stack()[1][0])
if isLog('trace'):
print(iColor('TRACE:'.ljust(maxlen(log_functions()) + 1), 'iBlack'),
log_fmt(caller),
*args, file=sys.stderr, **kwargs)
def debug(*args, **kwargs):
"""Prints csv DEBUG log to sys.stderr. Use it like print()"""
if not isDebug():
return
caller = getframeinfo(stack()[1][0])
if isLog('debug'):
print(iColor('DEBUG:'.ljust(maxlen(log_functions()) + 1), 'iYellow'),
log_fmt(caller),
*args, file=sys.stderr, **kwargs)
def info(*args, **kwargs):
"""Prints csv INFO log to sys.stderr. Use it like print()"""
caller = getframeinfo(stack()[1][0])
if isLog('info'):
print(iColor('INFO:'.ljust(maxlen(log_functions()) + 1), 'iGreen'),
log_fmt(caller),
*args, file=sys.stderr, **kwargs)
def success(*args, **kwargs):
"""Prints csv SUCCESS log to sys.stderr. Use it like print()"""
caller = getframeinfo(stack()[1][0])
if isLog('success'):
print(iColor('SUCCESS:'.ljust(maxlen(log_functions()) + 1), 'iGreen'),
log_fmt(caller),
*args, file=sys.stderr, **kwargs)
def warning(*args, **kwargs):
"""Prints csv WARNING log to sys.stderr. Use it like print()"""
caller = getframeinfo(stack()[1][0])
if isLog('warning'):
print(iColor('WARNING:'.ljust(maxlen(log_functions()) + 1), 'iRed'),
log_fmt(caller),
*args, file=sys.stderr, **kwargs)
def error(*args, **kwargs):
"""Prints csv ERROR log to sys.stderr. Use it like print()"""
caller = getframeinfo(stack()[1][0])
if isLog('error'):
print(iColor('ERROR:'.ljust(maxlen(log_functions()) + 1), 'iRed'),
log_fmt(caller),
*args, file=sys.stderr, **kwargs)
def abort(*args, **kwargs):
"""Prints csv ABORT log to sys.stderr. Use it like print()"""
caller = getframeinfo(stack()[1][0])
if isLog('critical'):
print(iColor('ABORT:'.ljust(maxlen(log_functions()) + 1), 'iRed'),
log_fmt(caller),
*args, file=sys.stderr, **kwargs)
if get_config('UNITTEST'):
return
sys.exit(1)
def sysExit(*args, **kwargs):
"""Prints csv EXIT log to sys.stderr. Use it like print()"""
caller = getframeinfo(stack()[1][0])
if isLog('critical'):
print(iColor('EXIT:'.ljust(maxlen(log_functions()) + 1), 'iGreen'),
log_fmt(caller),
*args, file=sys.stderr, **kwargs)
if get_config('UNITTEST'):
return
sys.exit(0)
def get_caller_lineno():
"""Returns caller line number"""
frame, _, lineno, _, _, _ = inspect.stack()[1]
return lineno
def isDebug():
"""Returns True is log level is DEBUG"""
return isLog('debug')
def isTrace():
"""Returns True is log level is TRACE"""
return isLog('trace')
def isFile(file):
"""Returns True if 'file' is file"""
return os.path.isfile(file)
def isFolder(path):
"""Returns True if 'path' exist"""
return os.path.exists(path)
def whichLog():
"""Returns current log"""
return cur_log()
def whichPlatform():
"""Returns system platform"""
return platform.system()
# API
def api_req(statusCode: int = 200, message=None, data=None):
"""Returns api request object of data
Args:
statusCode (int): any valid http status code {2xx, 3xx, 4xx, 5xx}
message (any): will add to body.Message
data (any): will be added to body.Data
"""
api_data = {
'Message': message,
'Data': data
}
return {
"statusCode": statusCode,
"headers": {
"Content-Type": "application/json"
},
"body": json.dumps(api_data, default=str)
}
def api_res(data, full=False):
"""Returns json object of api response"""
res = {}
for key in data.keys():
try:
res[key] = json.loads(data[key])
except Exception as err:
res[key] = data[key]
if not full and 'body' in res and 'Data' in res['body']:
return res['body']['Data']
return res
def isVenv():
"""Returns True if VIRTUAL_ENV is an env var"""
return 'VIRTUAL_ENV' in os.environ
def isLocal(): return 'bamdad' in cur_dir()['Path']
def get_host_data():
"""Returns dict of FQDN, Host IP & Host Name"""
return {
'fqdn': socket.getfqdn(),
'hostip': socket.gethostbyname(socket.gethostname()),
'hostname': socket.gethostname(),
}
# Folder Management
def cur_dir():
"""Returns dict of current directory & runing file info
Return:
{
CWD (str): Current working directory
Path (str): Current Path
File (str): Current file who called function
FileName (str): Current filename
Name (str): Current filename name - without ext
Platform (str): Current platform
}
"""
caller_frame = inspect.stack()[1]
file = caller_frame.filename
fullPath = os.path.realpath(file)
path, filename = os.path.split(fullPath)
res = {
'CWD': os.getcwd(),
'Path': path,
'File': file,
'FileName': filename,
'Name': os.path.splitext(filename)[0],
'Platform': platform.system(),
}
for k in res.keys():
res[k] = uni_path(res[k])
return res
def cur_file(path=None, prefix=None):
"""Returns current file with given 'path' & 'prefix'"""
path = f'{path}/' if path else ''
prefix = f'{prefix}-' if prefix else ''
caller_frame = inspect.stack()[1]
file = caller_frame.filename
fullPath = os.path.realpath(file)
iPath, filename = os.path.split(fullPath)
res = os.path.splitext(filename)[0]
return f'{path}{prefix}{res}'
def dot_path(path):
"""Returns linux path"""
return path.replace('\\', '/').replace('/./', '/').replace('/', '.')
def mk_folder(path):
"""Make folder if not exists"""
if not os.path.exists(path):
os.makedirs(path)
def rm_empty_folder(path):
"""Remove folder if exists"""
if not os.path.exists(path):
return
folders = list(os.walk(path))
for folder in folders:
# print ('all folder ->', folder)
if not folder[2]:
os.rmdir(folder[0])
def uni_path(path=''):
"""Returns linux path as universal path for any of OSX, Linux & Windows OS"""
return path.replace('\\', '/').replace('/./', '/')
def clean_path(path):
"""Returns removed '../' from given absolute path"""
path = uni_path(path)
paths = path.split('/')
while '..' in paths:
if paths[0] == '..':
break
for i, path in enumerate(paths):
trace(f'{i} : {path}')
if path == '..':
trace(f'{i} : {path} in path! pop({paths[i]})')
trace(f'{i} : {path} in path! pop({paths[i-1]})')
paths.pop(i)
paths.pop(i - 1)
trace(f"new path: {'/'.join(paths)}")
res = '/'.join(paths)
return res
# Print util
def fmt_aws_acc(accoount_id):
"""Returns nnnn-nnnn-nnnn format"""
acc = f'{accoount_id:012}'
return f'{acc[0:4]}-{acc[4:8]}-{acc[8:12]}'
def terminal_size():
"""Returns dict of terminal columns & lines size
{
'columns': int,
'lines': int
}
"""
ts = os.get_terminal_size()
return {
'columns': ts.columns,
'lines': ts.lines
}
def blue_green(lstr, rstr, sep=' ', lcol='Blue', rcol='Green'):
"""Returns blue lstr + sep + green rstr """
return iColor(str(lstr), lcol) + sep + iColor(str(rstr), rcol)
def blue_green_dict_print(data: dict, sep=' ', lcol='Blue', rcol='Green'):
"""Prints dict items in two colors"""
width = maxlen(data.keys())
for key in data.keys():
print(blue_green(key.ljust(width),
data[key], sep=sep, lcol=lcol, rcol=rcol))
def round_down(number: float, decimals: int = 0) -> float:
"""Rounds a number down to the given number of decimals."""
factor = 10 ** decimals
return math.floor(number * factor) / factor
def round_up(number: float, decimals: int = 0) -> float:
"""Rounds a number up to the given number of decimals."""
factor = 10 ** decimals
return math.ceil(number * factor) / factor
def justc(string: int | str, width: int = 3, trunk: bool = False) -> str:
"""Centers or truncates a string to a given width."""
string = str(string)
if len(string) <= width:
return string.center(width)
if trunk:
return textwrap.shorten(string, width - 3) + "..."
return string
def justl(string: int | str, width: int = 3, trunk: bool = False) -> str:
"""Left aligns or truncates a string to a given width."""
string = str(string)
if len(string) <= width:
return string
if trunk:
return textwrap.shorten(string, width - 3) + "..."
padding = width - len(string)
return string + " " * padding
def justr(string: int | str, width: int = 3, trunk: bool = False) -> str:
"""Right aligns or truncates a string to a given width."""
string = str(string)
if len(string) <= width:
return string + " " * (width - len(string))
if trunk:
return textwrap.shorten(string, width - 3) + "..."
padding = width - len(string)
return " " * padding + string
def maxlen(iVars=[]):
"""Returns maximum length of list elements"""
res = 0
for var in iVars:
res = max([len(var), res])
return res
def ndigits(string, width=3):
"""Returns zero leading string or num"""
return '0' * (width - len(str(string))) + str(string) if len(str(string)) < width else str(string)
def progress_print(counter=8, indent=8, limit=88, char='.'):
if counter == indent:
sys.stdout.write(' ' * indent)
counter += 1
if counter > limit:
print()
counter = indent
else:
sys.stdout.write('.')
sys.stdout.flush()
return counter
def ppwide(string, rep: str | None = None, lead: int | None = None, width: int | None = None):
"""Prints ~~~ Title ~~~~~ to desired 'width'
Args:
string (str | int): input string. If is single character then output is its replication.
rep (str | None): character to replicate to the desired width, default '#'
lead (int | None): leading character length with value of rep, default 3
width (int | None): desired width, default 90
Returns:
Returns string followed by a space and desired replication character to desired space
"""
if string is None:
string = get_config('REP')
if rep is None:
rep = get_config('REP')
if lead is None:
lead = get_config('LEAD')
if lead > 0 and len(string) > 0:
string = f'{rep*lead} {string}'
if width is None:
width = get_config('WIDTH')
print(to_len(string, rep=rep, width=width))
def to_space(string, width=3):
"""Returns left spaced string to given width"""
return ' ' * (width - len(str(string))) + str(string) if len(str(string)) < width else str(string)
def to_len(string: str, **kwargs) -> str:
"""Returns string followed by a space and dashed to desired space
Args:
string (str | int): input string. If is single character then output is its replication.
**kwargs:
rep (str): character to replicate to the desired width. Default '-'.
width (int): desired width. Default 90.
Returns:
Returns string followed by a space and desired replication character to desired space
"""
string = str(string)
rep = kwargs.get('rep', get_config('REP'))
width = kwargs.get('width', get_config('WIDTH'))
spc = ' '
if len(str(string)) == 1:
rep = spc = string
return f"{str(string)}{spc}{rep*(width-len(str(string))-1)}" if len(string) < width else string
def wline(rep='-', width: int | None = None):
"""Prints wide line filled with 'rep' to given 'width'"""
if width is None:
width = get_config('WIDTH')
ppwide(string=rep, rep=rep, lead=0, width=width)
# Colors
def colors():
"""Returns list of colors"""
return [
'Black', # Black
'Gray', # Gray
'Red', # Red
'Green', # Green
'Yellow', # Yellow
'Blue', # Blue
'Magenta', # Magenta
'Cyan', # Cyan
'White', # White
'iBlack', # Light Black
'iGray', # Light Gray
'iRed', # Light Red
'iGreen', # Light Green
'iYellow', # Light Yellow
'iBlue', # Light Blue
'iMagenta', # Light Magenta
'iCyan', # Light Cyan
'iWhite', # Light White
]
def iColors():
"""Returns list of extended colors"""
return [
'LIGHTBLACK_EX',
'LIGHTRED_EX',
'LIGHTGREEN_EX',
'LIGHTYELLOW_EX',
'LIGHTBLUE_EX',
'LIGHTMAGENTA_EX',
'LIGHTCYAN_EX',
'LIGHTWHITE_EX',
]
def cStyles():
"""Returns list of styles"""
return [
'DIM',
'NORMAL',
'BRIGHT',
]
def iColor(string, color, cStyle: str = 'Normal', trace=False):
"""Returns color formated string to use in print()
Args:
string (str | int): input string
color (str): one of 'Black' 'Gray' 'Red' 'Green' 'Yellow' 'Blue' 'Magenta' 'Cyan' 'White'
'iBlack' 'iGray' 'iRed' 'iGreen' 'iYellow' 'iBlue' 'iMagenta' 'iCyan' 'iWhite'
cStyle (str): one of 'DIM' 'NORMAL' 'BRIGHT'. Default 'NORMAL'
Caution:
Do not use log like trace or error here since it causes infinite loop
"""
if not get_config('COLORED'):
return string
iLocals = locals()
ln = get_caller_lineno() - 14 # go back to the function name
string = str(string)
cTitle = color.title()
if cTitle[0:1] == 'I':
cTitle = color[0:1].lower() + color[1:].title()
cTitle = cTitle.replace('Gray', 'Black')
cTitle = cTitle.replace('iGray', 'iBlack')
sColor = None
paint = None
nc = getattr(Style, 'RESET_ALL')
if cTitle[0:1] == 'i':
sColor = f'LIGHT{cTitle[1:].upper()}_EX'
if sColor in iColors():
paint = getattr(Fore, sColor)
elif cTitle in colors():
paint = getattr(Fore, cTitle.upper())
styles = ['DIM', 'NORMAL', 'BRIGHT']
if cStyle.upper() in styles:
sString = cStyle.title()
else:
sString = 'NORMAL' # set to default for invalid entry
cStyle = getattr(Style, cStyle.upper())
tab = ' ' * 6
if trace is True:
caller = getframeinfo(stack()[1][0])
this = inspect.stack()[0][3]
if caller.function not in log_functions():
iStyle = getattr(Style, 'NORMAL')
iPaint = getattr(Fore, 'YELLOW')
trace_log = {
'Color': color,
'cTitle': cTitle,
'sColor': sColor,
'cStyle': sString,
'paint': paint,
'string': string,
'nc': nc,
}
print(f'{iPaint}{iStyle}TRACE:{nc} File {caller.filename}, line {caller.lineno}', file=sys.stderr)
print(tab, f'1. Calling line {ln}: {this}({iLocals})', file=sys.stderr)
print(tab, f'2. Process: {trace_log}', file=sys.stderr)
print(tab, f'3. Returns: {paint}{cStyle}{string}{nc}', file=sys.stderr)
if paint:
return f"{paint}{cStyle}{string}{nc}"
return string
def incolor(string, color, cStyle='Normal'):
"""Identical to iColor() for backward compatiblity"""
return incolor(string, color, cStyle='Normal')
def triStateColor(string, cond=None):
"""Returns in Green, Red or Yellow for True, False or else cond"""
if cond is True:
return iColor(string, 'iGreen')
if cond is False:
return iColor(string, 'iRed')
return iColor(string, 'iYellow')
def rStyles():
"""Returns rich styles dict"""
return {
'': 'normal',
'b': 'bold',
'i': 'italic',
'l': 'blink',
'u': 'underline',
}
def rColors():
"""Returns list of rich colors abbrivations"""
res = []
colors = [
'Black', # Black
'Red', # Red
'Green', # Green
'Yellow', # Yellow
'Blue', # Blue
'Magenta', # Magenta
'Cyan', # Cyan
'White', # White
'Bright_Black', # Bright Black
'Bright_Red', # Bright Red
'Bright_Green', # Bright Green
'Bright_Yellow', # Bright Yellow
'Bright_Blue', # Bright Blue
'Bright_Magenta', # Bright Magenta
'Bright_Cyan', # Bright Cyan
'Bright_White', # Bright White
]
bright = ''
for key in rStyles().keys():
for color in colors:
res.append(f'{key}{color}')
return res
def rColor(string, color):
"""Returns rich color only usable with console.print() or rprint
Arguments:
string (any): string to paint with color
color (str): any valid rich color in format of [b|i|l|u]['Bright_']Color
---
#### Valid rich Color is one of:
Black, Red, Green, Yellow, Blue, Magenta, Cyan, White
---
#### Valid rich Prefix for Color is one of:
'': 'normal', 'b': 'bold', 'i': 'italic', 'l': 'blink', 'u': 'underline',
"""
if not get_config('COLORED'):
return string
# styles = ['blink', 'bold', 'italic', 'underline']
style = ''
for key, val in rStyles().items():
if color[0] == key:
style = val
if color[0] == color[0].lower():
color = color[1:]
if 'Gray' in color:
color.replace('Gray', 'Black')
if 'Blue' in color:
color = 'Dodger_Blue1'
if 'Yellow' in color:
color = f'color({11})'
if 'Magenta' in color:
color = f'color({13})'
# if color[0] == 'i':
# color = 'Bright_'+color[1:]
color = color.strip()
string = f'[{color.lower()} {style}]{string}'
return string
def rprint(string, color: None | str = None):
if color is None:
print(string)
return
color = rColor(color)
console.print(string, color)
# File Management
def rm_file(file):
"""Remove file is exists"""
if os.path.isfile(file):
os.remove(file)
return os.path.isfile(file)
def file_read_lines(file) -> list:
"""Returns list of lines for given file"""
try:
with open(file) as f:
rs = f.readlines()
res = []
for r in rs:
r = r.replace('\r\n', '').replace('\n', '').strip()
res.append(r)
return res
except Exception as err:
error('utils.file_read_lines, file:', file, err)
return []
def get_dir(path: str | None):
"""Returns dict of Dirs & Files for path of [start][*][.ext]
Args:
path (str): path to search or [start][*][.ext]
"""
res = {'Path': '', 'Dirs': [], 'Files': [], 'Paths': []}
if not path:
path = cur_dir()['Path']
full_path = clean_path(path)
paths = full_path.split('/')
filter = paths[-1]
paths.pop(-1)
path = '/'.join(paths)
res['Path'] = path
files = os.listdir(path)
files = [f for f in files if os.path.isfile(path + '/' + f)]
res['Dirs'] = [d for d in files if os.path.isdir(path + '/' + d)]
start = end = None
if filter.startswith('.'):
debug('.')
end = filter
if filter.startswith('*'):
debug('*')
filter = filter[1:]
end = filter
if '*' in filter[1:]:
debug('start * end')
filters = filter.split('*')
start = filters[0]
end = filter[-1]
# filtered files
for file in files:
if start and end:
if file.startswith(start) and file.endswith(end):
debug('start & end', file)
res['Files'].append(file)
elif start:
if file.startswith(start):
debug('start', file)
res['Files'].append(file)
elif end:
if file.endswith(end):
debug('end', file)
res['Files'].append(file)
# filtered paths
for file in res['Files']:
res['Paths'].append(path + '/' + file)
return res
def file_append_line(file, line):
"""Append a line to given file"""
try:
with open(file, 'a') as f:
f.write(str(line) + '\n')
return True
except Exception as err:
error('utils.file_append_line, file:',
file, 'line:', line, 'error:', err)
return False
def get_file(file):
"""Returns file content"""
try:
with open(file, 'r') as f:
res = f.read()
return res
except Exception as err:
error('utils.get_file, file:', file, 'error:', err)
return False # type: ignore
def put_file(file, data):
"""Create or rewite a file with given 'data'"""
try: