forked from GameMaker2k/PyCatFile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyarchivefile.py
executable file
·10564 lines (9995 loc) · 448 KB
/
pyarchivefile.py
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
# -*- coding: UTF-8 -*-
'''
This program is free software; you can redistribute it and/or modify
it under the terms of the Revised BSD License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Revised BSD License for more details.
Copyright 2018-2024 Cool Dude 2k - http://idb.berlios.de/
Copyright 2018-2024 Game Maker 2k - http://intdb.sourceforge.net/
Copyright 2018-2024 Kazuki Przyborowski - https://github.com/KazukiPrzyborowski
$FileInfo: pyarchivefile.py - Last Update: 2/7/2025 Ver. 0.18.2 RC 1 - Author: cooldude2k $
'''
from __future__ import absolute_import, division, print_function, unicode_literals, generators, with_statement, nested_scopes
import io
import os
import re
import sys
import time
import stat
import zlib
import base64
import shutil
import socket
import hashlib
import inspect
import datetime
import logging
import zipfile
import binascii
import platform
try:
from backports import tempfile
except ImportError:
import tempfile
# FTP Support
ftpssl = True
try:
from ftplib import FTP, FTP_TLS
except ImportError:
ftpssl = False
from ftplib import FTP
try:
import ujson as json
except ImportError:
try:
import simplejson as json
except ImportError:
import json
try:
import configparser
except ImportError:
try:
import SafeConfigParser as configparser
except ImportError:
import ConfigParser as configparser
try:
file
except NameError:
from io import IOBase
file = IOBase
#if isinstance(outfile, file) or isinstance(outfile, IOBase):
try:
basestring
except NameError:
basestring = str
baseint = []
try:
baseint.append(long)
baseint.insert(0, int)
except NameError:
baseint.append(int)
baseint = tuple(baseint)
# URL Parsing
try:
from urllib.parse import urlparse, urlunparse
except ImportError:
from urlparse import urlparse, urlunparse
# Windows-specific setup
if os.name == 'nt':
if sys.version_info[0] == 2:
import codecs
sys.stdout = codecs.getwriter('UTF-8')(sys.stdout)
sys.stderr = codecs.getwriter('UTF-8')(sys.stderr)
else:
sys.stdout = io.TextIOWrapper(
sys.stdout.buffer, encoding='UTF-8', errors='replace', line_buffering=True)
sys.stderr = io.TextIOWrapper(
sys.stderr.buffer, encoding='UTF-8', errors='replace', line_buffering=True)
hashlib_guaranteed = False
# Environment setup
os.environ["PYTHONIOENCODING"] = "UTF-8"
# Reload sys to set default encoding to UTF-8 (Python 2 only)
if sys.version_info[0] == 2:
try:
reload(sys)
sys.setdefaultencoding('UTF-8')
except (NameError, AttributeError):
pass
# CRC32 import
try:
from zlib import crc32
except ImportError:
from binascii import crc32
# Define FileNotFoundError for Python 2
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
# RAR file support
rarfile_support = False
try:
import rarfile
rarfile_support = True
except ImportError:
pass
except OSError:
pass
# 7z file support
py7zr_support = False
try:
import py7zr
py7zr_support = True
except ImportError:
pass
except OSError:
pass
# TAR file checking
try:
from xtarfile import is_tarfile
except ImportError:
try:
from safetar import is_tarfile
except ImportError:
from tarfile import is_tarfile
# TAR file module
try:
import xtarfile as tarfile
except ImportError:
try:
import safetar as tarfile
except ImportError:
import tarfile
# Paramiko support
haveparamiko = False
try:
import paramiko
haveparamiko = True
except ImportError:
pass
except OSError:
pass
# PySFTP support
havepysftp = False
try:
import pysftp
havepysftp = True
except ImportError:
pass
except OSError:
pass
# Add the mechanize import check
havemechanize = False
try:
import mechanize
havemechanize = True
except ImportError:
pass
except OSError:
pass
# Requests support
haverequests = False
try:
import requests
haverequests = True
import urllib3
logging.getLogger("urllib3").setLevel(logging.WARNING)
except ImportError:
pass
except OSError:
pass
# HTTPX support
havehttpx = False
try:
import httpx
havehttpx = True
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
except ImportError:
pass
except OSError:
pass
# HTTP and URL parsing
try:
from urllib.request import Request, build_opener, HTTPBasicAuthHandler
from urllib.parse import urlparse
except ImportError:
from urllib2 import Request, build_opener, HTTPBasicAuthHandler
from urlparse import urlparse
# StringIO and BytesIO
try:
from io import StringIO, BytesIO
except ImportError:
try:
from cStringIO import StringIO
from cStringIO import StringIO as BytesIO
except ImportError:
from StringIO import StringIO
from StringIO import StringIO as BytesIO
def get_importing_script_path():
# Inspect the stack and get the frame of the caller
stack = inspect.stack()
for frame_info in stack:
# In Python 2, frame_info is a tuple; in Python 3, it's a named tuple
filename = frame_info[1] if isinstance(frame_info, tuple) else frame_info.filename
if filename != __file__: # Ignore current module's file
return os.path.abspath(filename)
return None
def get_default_threads():
"""Returns the number of CPU threads available, or 1 if unavailable."""
try:
cpu_threads = os.cpu_count()
return cpu_threads if cpu_threads is not None else 1
except AttributeError:
# os.cpu_count() might not be available in some environments
return 1
__use_pysftp__ = False
__use_alt_format__ = False
__use_env_file__ = True
__use_ini_file__ = True
__use_ini_name__ = "archivefile.ini"
if('PYCATFILE_CONFIG_FILE' in os.environ and os.path.exists(os.environ['PYCATFILE_CONFIG_FILE']) and __use_env_file__):
scriptconf = os.environ['PYCATFILE_CONFIG_FILE']
else:
prescriptpath = get_importing_script_path()
if(prescriptpath is not None):
scriptconf = os.path.join(os.path.dirname(prescriptpath), __use_ini_name__)
else:
scriptconf = ""
if os.path.exists(scriptconf):
__config_file__ = scriptconf
else:
__config_file__ = os.path.join(os.path.dirname(os.path.realpath(__file__)), __use_ini_name__)
if(not havepysftp):
__use_pysftp__ = False
__use_http_lib__ = "httpx"
if(__use_http_lib__ == "httpx" and haverequests and not havehttpx):
__use_http_lib__ = "requests"
if(__use_http_lib__ == "requests" and havehttpx and not haverequests):
__use_http_lib__ = "httpx"
if((__use_http_lib__ == "httpx" or __use_http_lib__ == "requests") and not havehttpx and not haverequests):
__use_http_lib__ = "urllib"
# Define a function to check if var contains only non-printable chars
all_np_chars = [chr(i) for i in range(128)]
def is_only_nonprintable(var):
return all(not c.isprintable() for c in var)
__file_format_multi_dict__ = {}
__file_format_default__ = "ArchiveFile"
__include_defaults__ = True
__program_name__ = "Py"+__file_format_default__
if __use_ini_file__ and os.path.exists(__config_file__):
config = configparser.ConfigParser()
config.read(__config_file__)
def decode_unicode_escape(value):
if sys.version_info[0] < 3: # Python 2
return value.decode('unicode_escape')
else: # Python 3
return bytes(value, 'UTF-8').decode('unicode_escape')
__file_format_default__ = decode_unicode_escape(config.get('config', 'default'))
__program_name__ = decode_unicode_escape(config.get('config', 'proname'))
__include_defaults__ = config.getboolean('config', 'includedef')
# Loop through all sections
for section in config.sections():
required_keys = [
"len", "hex", "ver", "name",
"magic", "delimiter", "extension",
"newstyle", "advancedlist", "altinode"
]
if section != "config" and all(key in config[section] for key in required_keys):
delim = decode_unicode_escape(config.get(section, 'delimiter'))
if(not is_only_nonprintable(delim)):
delim = "\x00" * len("\x00")
__file_format_multi_dict__.update( { decode_unicode_escape(config.get(section, 'magic')): {'format_name': decode_unicode_escape(config.get(section, 'name')), 'format_magic': decode_unicode_escape(config.get(section, 'magic')), 'format_len': config.getint(section, 'len'), 'format_hex': config.get(section, 'hex'), 'format_delimiter': delim, 'format_ver': config.get(section, 'ver'), 'new_style': config.getboolean(section, 'newstyle'), 'use_advanced_list': config.getboolean(section, 'advancedlist'), 'use_alt_inode': config.getboolean(section, 'altinode'), 'format_extension': decode_unicode_escape(config.get(section, 'extension')) } } )
if not __file_format_multi_dict__ and not __include_defaults__:
__include_defaults__ = True
elif __use_ini_file__ and not os.path.exists(__config_file__):
__use_ini_file__ = False
__include_defaults__ = True
if not __use_ini_file__ and not __include_defaults__:
__include_defaults__ = True
if(__include_defaults__):
if("ArchiveFile" not in __file_format_multi_dict__):
__file_format_multi_dict__.update( { 'ArchiveFile': {'format_name': "ArchiveFile", 'format_magic': "ArchiveFile", 'format_len': 11, 'format_hex': "4172636869766546696c65", 'format_delimiter': "\x00", 'format_ver': "001", 'new_style': True, 'use_advanced_list': True, 'use_alt_inode': False, 'format_extension': ".arc" } } )
if(__file_format_default__ not in __file_format_multi_dict__):
__file_format_default__ = next(iter(__file_format_multi_dict__))
__file_format_name__ = __file_format_multi_dict__[__file_format_default__]['format_name']
__file_format_magic__ = __file_format_multi_dict__[__file_format_default__]['format_magic']
__file_format_len__ = __file_format_multi_dict__[__file_format_default__]['format_len']
__file_format_hex__ = __file_format_multi_dict__[__file_format_default__]['format_hex']
__file_format_delimiter__ = __file_format_multi_dict__[__file_format_default__]['format_delimiter']
__file_format_ver__ = __file_format_multi_dict__[__file_format_default__]['format_ver']
__use_new_style__ = __file_format_multi_dict__[__file_format_default__]['new_style']
__use_advanced_list__ = __file_format_multi_dict__[__file_format_default__]['use_advanced_list']
__use_alt_inode__ = __file_format_multi_dict__[__file_format_default__]['use_alt_inode']
__file_format_extension__ = __file_format_multi_dict__[__file_format_default__]['format_extension']
__file_format_dict__ = __file_format_multi_dict__[__file_format_default__]
__project__ = __program_name__
__project_url__ = "https://github.com/GameMaker2k/PyArchiveFile"
__version_info__ = (0, 18, 2, "RC 1", 1)
__version_date_info__ = (2025, 2, 7, "RC 1", 1)
__version_date__ = str(__version_date_info__[0]) + "." + str(
__version_date_info__[1]).zfill(2) + "." + str(__version_date_info__[2]).zfill(2)
__revision__ = __version_info__[3]
__revision_id__ = "$Id$"
if(__version_info__[4] is not None):
__version_date_plusrc__ = __version_date__ + \
"-" + str(__version_date_info__[4])
if(__version_info__[4] is None):
__version_date_plusrc__ = __version_date__
if(__version_info__[3] is not None):
__version__ = str(__version_info__[0]) + "." + str(__version_info__[
1]) + "." + str(__version_info__[2]) + " " + str(__version_info__[3])
if(__version_info__[3] is None):
__version__ = str(__version_info__[
0]) + "." + str(__version_info__[1]) + "." + str(__version_info__[2])
PyBitness = platform.architecture()
if(PyBitness == "32bit" or PyBitness == "32"):
PyBitness = "32"
elif(PyBitness == "64bit" or PyBitness == "64"):
PyBitness = "64"
else:
PyBitness = "32"
geturls_ua_pyarchivefile_python = "Mozilla/5.0 (compatible; {proname}/{prover}; +{prourl})".format(
proname=__project__, prover=__version__, prourl=__project_url__)
if(platform.python_implementation() != ""):
py_implementation = platform.python_implementation()
if(platform.python_implementation() == ""):
py_implementation = "Python"
geturls_ua_pyarchivefile_python_alt = "Mozilla/5.0 ({osver}; {archtype}; +{prourl}) {pyimp}/{pyver} (KHTML, like Gecko) {proname}/{prover}".format(osver=platform.system(
)+" "+platform.release(), archtype=platform.machine(), prourl=__project_url__, pyimp=py_implementation, pyver=platform.python_version(), proname=__project__, prover=__version__)
geturls_ua_googlebot_google = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
geturls_ua_googlebot_google_old = "Googlebot/2.1 (+http://www.google.com/bot.html)"
geturls_headers_pyarchivefile_python = {'Referer': "http://google.com/", 'User-Agent': geturls_ua_pyarchivefile_python, 'Accept-Encoding': "none", 'Accept-Language': "en-US,en;q=0.8,en-CA,en-GB;q=0.6", 'Accept-Charset': "ISO-8859-1,ISO-8859-15,UTF-8;q=0.7,*;q=0.7", 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 'Connection': "close",
'SEC-CH-UA': "\""+__project__+"\";v=\""+str(__version__)+"\", \"Not;A=Brand\";v=\"8\", \""+py_implementation+"\";v=\""+str(platform.release())+"\"", 'SEC-CH-UA-FULL-VERSION': str(__version__), 'SEC-CH-UA-PLATFORM': ""+py_implementation+"", 'SEC-CH-UA-ARCH': ""+platform.machine()+"", 'SEC-CH-UA-PLATFORM': str(__version__), 'SEC-CH-UA-BITNESS': str(PyBitness)}
geturls_headers_pyarchivefile_python_alt = {'Referer': "http://google.com/", 'User-Agent': geturls_ua_pyarchivefile_python_alt, 'Accept-Encoding': "none", 'Accept-Language': "en-US,en;q=0.8,en-CA,en-GB;q=0.6", 'Accept-Charset': "ISO-8859-1,ISO-8859-15,UTF-8;q=0.7,*;q=0.7", 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 'Connection': "close",
'SEC-CH-UA': "\""+__project__+"\";v=\""+str(__version__)+"\", \"Not;A=Brand\";v=\"8\", \""+py_implementation+"\";v=\""+str(platform.release())+"\"", 'SEC-CH-UA-FULL-VERSION': str(__version__), 'SEC-CH-UA-PLATFORM': ""+py_implementation+"", 'SEC-CH-UA-ARCH': ""+platform.machine()+"", 'SEC-CH-UA-PLATFORM': str(__version__), 'SEC-CH-UA-BITNESS': str(PyBitness)}
geturls_headers_googlebot_google = {'Referer': "http://google.com/", 'User-Agent': geturls_ua_googlebot_google, 'Accept-Encoding': "none", 'Accept-Language': "en-US,en;q=0.8,en-CA,en-GB;q=0.6",
'Accept-Charset': "ISO-8859-1,ISO-8859-15,UTF-8;q=0.7,*;q=0.7", 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 'Connection': "close"}
geturls_headers_googlebot_google_old = {'Referer': "http://google.com/", 'User-Agent': geturls_ua_googlebot_google_old, 'Accept-Encoding': "none", 'Accept-Language': "en-US,en;q=0.8,en-CA,en-GB;q=0.6",
'Accept-Charset': "ISO-8859-1,ISO-8859-15,UTF-8;q=0.7,*;q=0.7", 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 'Connection': "close"}
compressionsupport = []
try:
import gzip
compressionsupport.append("gz")
compressionsupport.append("gzip")
except ImportError:
pass
try:
import bz2
compressionsupport.append("bz2")
compressionsupport.append("bzip2")
except ImportError:
pass
try:
import lz4
import lz4.frame
compressionsupport.append("lz4")
except ImportError:
pass
try:
import lzo
compressionsupport.append("lzo")
compressionsupport.append("lzop")
except ImportError:
pass
try:
import zstandard
compressionsupport.append("zst")
compressionsupport.append("zstd")
compressionsupport.append("zstandard")
except ImportError:
try:
import pyzstd.zstdfile
compressionsupport.append("zst")
compressionsupport.append("zstd")
compressionsupport.append("zstandard")
except ImportError:
pass
try:
import lzma
compressionsupport.append("lzma")
compressionsupport.append("xz")
except ImportError:
try:
from backports import lzma
compressionsupport.append("lzma")
compressionsupport.append("xz")
except ImportError:
pass
compressionsupport.append("zlib")
compressionsupport.append("zl")
compressionsupport.append("zz")
compressionlist = ['auto']
compressionlistalt = []
outextlist = []
outextlistwd = []
if('gzip' in compressionsupport):
compressionlist.append('gzip')
compressionlistalt.append('gzip')
outextlist.append('gz')
outextlistwd.append('.gz')
if('bzip2' in compressionsupport):
compressionlist.append('bzip2')
compressionlistalt.append('bzip2')
outextlist.append('bz2')
outextlistwd.append('.bz2')
if('zstd' in compressionsupport):
compressionlist.append('zstd')
compressionlistalt.append('zstd')
outextlist.append('zst')
outextlistwd.append('.zst')
if('lz4' in compressionsupport):
compressionlist.append('lz4')
compressionlistalt.append('lz4')
outextlist.append('lz4')
outextlistwd.append('.lz4')
if('lzo' in compressionsupport):
compressionlist.append('lzo')
compressionlistalt.append('lzo')
outextlist.append('lzo')
outextlistwd.append('.lzo')
if('lzop' in compressionsupport):
compressionlist.append('lzop')
compressionlistalt.append('lzop')
outextlist.append('lzop')
outextlistwd.append('.lzop')
if('lzma' in compressionsupport):
compressionlist.append('lzma')
compressionlistalt.append('lzma')
outextlist.append('lzma')
outextlistwd.append('.lzma')
if('xz' in compressionsupport):
compressionlist.append('xz')
compressionlistalt.append('xz')
outextlist.append('xz')
outextlistwd.append('.xz')
if('zlib' in compressionsupport):
compressionlist.append('zlib')
compressionlistalt.append('zlib')
outextlist.append('zz')
outextlistwd.append('.zz')
outextlist.append('zl')
outextlistwd.append('.zl')
outextlist.append('zlib')
outextlistwd.append('.zlib')
if __name__ == "__main__":
import subprocess
curscrpath = os.path.dirname(sys.argv[0])
if(curscrpath == ""):
curscrpath = "."
if(os.sep == "\\"):
curscrpath = curscrpath.replace(os.sep, "/")
curscrpath = curscrpath + "/"
scrfile = curscrpath + "archivefile.py"
if(os.path.exists(scrfile) and os.path.isfile(scrfile)):
scrcmd = subprocess.Popen([sys.executable, scrfile] + sys.argv[1:])
scrcmd.wait()
def VerbosePrintOut(dbgtxt, outtype="log", dbgenable=True, dgblevel=20):
if(not dbgenable):
return True
log_functions = {
"print": print,
"log": logging.info,
"warning": logging.warning,
"error": logging.error,
"critical": logging.critical,
"exception": logging.exception,
"logalt": lambda x: logging.log(dgblevel, x),
"debug": logging.debug
}
log_function = log_functions.get(outtype)
if(log_function):
log_function(dbgtxt)
return True
return False
def VerbosePrintOutReturn(dbgtxt, outtype="log", dbgenable=True, dgblevel=20):
VerbosePrintOut(dbgtxt, outtype, dbgenable, dgblevel)
return dbgtxt
def RemoveWindowsPath(dpath):
"""
Normalizes a path by converting Windows-style separators to Unix-style and stripping trailing slashes.
"""
if dpath is None:
dpath = ""
if os.sep != "/":
dpath = dpath.replace(os.path.sep, "/")
dpath = dpath.rstrip("/")
if dpath in [".", ".."]:
dpath = dpath + "/"
return dpath
def NormalizeRelativePath(inpath):
"""
Ensures the path is relative unless it is absolute. Prepares consistent relative paths.
"""
inpath = RemoveWindowsPath(inpath)
if os.path.isabs(inpath):
outpath = inpath
else:
if inpath.startswith("./") or inpath.startswith("../"):
outpath = inpath
else:
outpath = "./" + inpath
return outpath
def PrependPath(base_dir, child_path):
# Check if base_dir is None or empty, if so, return child_path as is
if not base_dir:
return child_path
# Ensure base_dir ends with exactly one slash
if not base_dir.endswith('/'):
base_dir += '/'
# Check if child_path starts with ./ or ../ (indicating a relative path)
if child_path.startswith('./') or child_path.startswith('../'):
# For relative paths, we don't alter the child_path
return base_dir + child_path
else:
# For non-relative paths, ensure there's no starting slash on child_path to avoid double slashes
return base_dir + child_path.lstrip('/')
def ListDir(dirpath, followlink=False, duplicates=False, include_regex=None, exclude_regex=None):
"""
Simplified directory listing function with regex support for inclusion and exclusion.
Compatible with Python 2 and 3.
Parameters:
dirpath (str or list): A string or list of directory paths to process.
followlink (bool): Whether to follow symbolic links (default: False).
duplicates (bool): Whether to include duplicate paths (default: False).
include_regex (str): Regex pattern to include matching files/directories (default: None).
exclude_regex (str): Regex pattern to exclude matching files/directories (default: None).
Returns:
list: A list of files and directories matching the criteria.
"""
try:
if os.stat not in os.supports_follow_symlinks and followlink:
followlink = False
except AttributeError:
followlink = False
if isinstance(dirpath, (list, tuple)):
dirpath = list(filter(None, dirpath))
elif isinstance(dirpath, basestring):
dirpath = list(filter(None, [dirpath]))
retlist = []
fs_encoding = sys.getfilesystemencoding() or 'UTF-8'
include_pattern = re.compile(include_regex) if include_regex else None
exclude_pattern = re.compile(exclude_regex) if exclude_regex else None
for mydirfile in dirpath:
if not os.path.exists(mydirfile):
return False
mydirfile = NormalizeRelativePath(mydirfile)
if os.path.exists(mydirfile) and os.path.islink(mydirfile) and followlink:
mydirfile = RemoveWindowsPath(os.path.realpath(mydirfile))
if os.path.exists(mydirfile) and os.path.isdir(mydirfile):
for root, dirs, filenames in os.walk(mydirfile):
dpath = RemoveWindowsPath(root)
if not isinstance(dpath, basestring):
dpath = dpath.decode(fs_encoding)
# Apply regex filtering for directories
if ((not include_pattern or include_pattern.search(dpath)) and
(not exclude_pattern or not exclude_pattern.search(dpath))):
if not duplicates and dpath not in retlist:
retlist.append(dpath)
elif duplicates:
retlist.append(dpath)
for files in filenames:
fpath = os.path.join(root, files)
fpath = RemoveWindowsPath(fpath)
if not isinstance(fpath, basestring):
fpath = fpath.decode(fs_encoding)
# Apply regex filtering for files
if ((not include_pattern or include_pattern.search(fpath)) and
(not exclude_pattern or not exclude_pattern.search(fpath))):
if not duplicates and fpath not in retlist:
retlist.append(fpath)
elif duplicates:
retlist.append(fpath)
else:
path = RemoveWindowsPath(mydirfile)
if not isinstance(path, basestring):
path = path.decode(fs_encoding)
# Apply regex filtering for single paths
if ((not include_pattern or include_pattern.search(path)) and
(not exclude_pattern or not exclude_pattern.search(path))):
retlist.append(path)
return retlist
def ListDirAdvanced(dirpath, followlink=False, duplicates=False, include_regex=None, exclude_regex=None):
"""
Advanced directory listing function with regex support for inclusion and exclusion.
Compatible with Python 2 and 3.
Parameters:
dirpath (str or list): A string or list of directory paths to process.
followlink (bool): Whether to follow symbolic links (default: False).
duplicates (bool): Whether to include duplicate paths (default: False).
include_regex (str): Regex pattern to include matching files/directories (default: None).
exclude_regex (str): Regex pattern to exclude matching files/directories (default: None).
Returns:
list: A list of files and directories matching the criteria.
"""
try:
if os.stat not in os.supports_follow_symlinks and followlink:
followlink = False
except AttributeError:
followlink = False
if isinstance(dirpath, (list, tuple)):
dirpath = list(filter(None, dirpath))
elif isinstance(dirpath, basestring):
dirpath = list(filter(None, [dirpath]))
retlist = []
fs_encoding = sys.getfilesystemencoding() or 'UTF-8'
include_pattern = re.compile(include_regex) if include_regex else None
exclude_pattern = re.compile(exclude_regex) if exclude_regex else None
for mydirfile in dirpath:
if not os.path.exists(mydirfile):
return False
mydirfile = NormalizeRelativePath(mydirfile)
if os.path.exists(mydirfile) and os.path.islink(mydirfile) and followlink:
mydirfile = RemoveWindowsPath(os.path.realpath(mydirfile))
if os.path.exists(mydirfile) and os.path.isdir(mydirfile):
for root, dirs, filenames in os.walk(mydirfile):
# Sort directories and files
dirs.sort(key=lambda x: x.lower())
filenames.sort(key=lambda x: x.lower())
dpath = RemoveWindowsPath(root)
if not isinstance(dpath, basestring):
dpath = dpath.decode(fs_encoding)
# Apply regex filtering for directories
if ((not include_pattern or include_pattern.search(dpath)) and
(not exclude_pattern or not exclude_pattern.search(dpath))):
if not duplicates and dpath not in retlist:
retlist.append(dpath)
elif duplicates:
retlist.append(dpath)
for files in filenames:
fpath = os.path.join(root, files)
fpath = RemoveWindowsPath(fpath)
if not isinstance(fpath, basestring):
fpath = fpath.decode(fs_encoding)
# Apply regex filtering for files
if ((not include_pattern or include_pattern.search(fpath)) and
(not exclude_pattern or not exclude_pattern.search(fpath))):
if not duplicates and fpath not in retlist:
retlist.append(fpath)
elif duplicates:
retlist.append(fpath)
else:
path = RemoveWindowsPath(mydirfile)
if not isinstance(path, basestring):
path = path.decode(fs_encoding)
# Apply regex filtering for single paths
if ((not include_pattern or include_pattern.search(path)) and
(not exclude_pattern or not exclude_pattern.search(path))):
retlist.append(path)
return retlist
def GetTotalSize(file_list):
"""
Calculate the total size of all files in the provided list.
Parameters:
file_list (list): List of file paths.
Returns:
int: Total size of all files in bytes.
"""
total_size = 0
for item in file_list:
if os.path.isfile(item): # Ensure it's a file
try:
total_size += os.path.getsize(item)
except OSError:
sys.stderr.write("Error accessing file {}: {}\n".format(item, e))
return total_size
def create_alias_function_alt(prefix, base_name, suffix, target_function, positional_overrides=None):
"""
Creates a new function in the global namespace that wraps 'target_function',
allowing optional overrides of specific positional arguments via 'positional_overrides'.
:param prefix: String prefix for the new function's name
:param base_name: Base string to use in the new function's name
:param suffix: String suffix for the new function's name
:param target_function: The function to be wrapped/aliased
:param positional_overrides: Optional dict {index: new_value} for overriding specific positional arguments
"""
# Define a new function that wraps the target function
def alias_function(*args, **kwargs):
# Convert args to a list so we can modify specific positions
args_list = list(args)
# If there are positional overrides, apply them
if positional_overrides:
for index, value in positional_overrides.items():
# Only apply if the index is within the bounds of the original arguments
if 0 <= index < len(args_list):
args_list[index] = value
# Call the target function with possibly modified arguments
return target_function(*args_list, **kwargs)
# Create the function name by combining the prefix, base name, and the suffix
function_name = "{}{}{}".format(prefix, base_name, suffix)
# Add the new function to the global namespace
globals()[function_name] = alias_function
def create_alias_function(prefix, base_name, suffix, target_function, positional_overrides=None):
"""
Creates a new function in the global namespace that wraps 'target_function',
allowing optional overrides of specific positional arguments via 'positional_overrides'.
:param prefix: String prefix for the new function's name
:param base_name: Base string to use in the new function's name
:param suffix: String suffix for the new function's name
:param target_function: The function to be wrapped/aliased
:param positional_overrides: Optional dict {index: new_value} for overriding specific positional arguments
"""
# Define a new function that wraps the target function
def alias_function(*args, **kwargs):
# Convert args to a list so we can modify specific positions
args_list = list(args)
# If there are positional overrides, apply them
if positional_overrides:
for index, value in positional_overrides.items():
if 0 <= index < len(args_list):
args_list[index] = value
# Call the target function with possibly modified arguments
return target_function(*args_list, **kwargs)
# Create the function name by combining the prefix, base_name, and suffix
function_name = "{}{}{}".format(prefix, base_name, suffix)
# Add the new function to the global namespace
globals()[function_name] = alias_function
class ZlibFile:
def __init__(self, file_path=None, fileobj=None, mode='rb', level=9, wbits=15, encoding=None, errors=None, newline=None):
if file_path is None and fileobj is None:
raise ValueError("Either file_path or fileobj must be provided")
if file_path is not None and fileobj is not None:
raise ValueError(
"Only one of file_path or fileobj should be provided")
self.file_path = file_path
self.fileobj = fileobj
self.mode = mode
self.level = level
self.wbits = wbits
self.encoding = encoding
self.errors = errors
self.newline = newline
self._compressed_data = b''
self._decompressed_data = b''
self._position = 0
self._text_mode = 't' in mode
# Force binary mode for internal handling
internal_mode = mode.replace('t', 'b')
if 'w' in mode or 'a' in mode or 'x' in mode:
self.file = open(
file_path, internal_mode) if file_path else fileobj
self._compressor = zlib.compressobj(level, zlib.DEFLATED, wbits)
elif 'r' in mode:
if file_path:
if os.path.exists(file_path):
self.file = open(file_path, internal_mode)
self._load_file()
else:
raise FileNotFoundError(
"No such file: '{}'".format(file_path))
elif fileobj:
self.file = fileobj
self._load_file()
else:
raise ValueError("Mode should be 'rb' or 'wb'")
def _load_file(self):
self.file.seek(0)
self._compressed_data = self.file.read()
if not self._compressed_data.startswith((b'\x78\x01', b'\x78\x5E', b'\x78\x9C', b'\x78\xDA')):
raise ValueError("Invalid zlib file header")
self._decompressed_data = zlib.decompress(
self._compressed_data, self.wbits)
if self._text_mode:
self._decompressed_data = self._decompressed_data.decode(
self.encoding or 'UTF-8', self.errors or 'strict')
def write(self, data):
if self._text_mode:
data = data.encode(self.encoding or 'UTF-8',
self.errors or 'strict')
compressed_data = self._compressor.compress(
data) + self._compressor.flush(zlib.Z_SYNC_FLUSH)
self.file.write(compressed_data)
def read(self, size=-1):
if size == -1:
size = len(self._decompressed_data) - self._position
data = self._decompressed_data[self._position:self._position + size]
self._position += size
return data
def seek(self, offset, whence=0):
if whence == 0: # absolute file positioning
self._position = offset
elif whence == 1: # seek relative to the current position
self._position += offset
elif whence == 2: # seek relative to the file's end
self._position = len(self._decompressed_data) + offset
else:
raise ValueError("Invalid value for whence")
# Ensure the position is within bounds
self._position = max(
0, min(self._position, len(self._decompressed_data)))
def tell(self):
return self._position
def flush(self):
self.file.flush()
def fileno(self):
if hasattr(self.file, 'fileno'):
return self.file.fileno()
raise OSError("The underlying file object does not support fileno()")
def isatty(self):
if hasattr(self.file, 'isatty'):
return self.file.isatty()
return False
def truncate(self, size=None):
if hasattr(self.file, 'truncate'):
return self.file.truncate(size)
raise OSError("The underlying file object does not support truncate()")
def close(self):
if 'w' in self.mode or 'a' in self.mode or 'x' in self.mode:
self.file.write(self._compressor.flush(zlib.Z_FINISH))
if self.file_path:
self.file.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def _gzip_compress(data, compresslevel=9):
"""
Compress data with a GZIP wrapper (wbits=31) in one shot.
:param data: Bytes to compress.
:param compresslevel: 1..9
:return: GZIP-compressed bytes.
"""
compobj = zlib.compressobj(compresslevel, zlib.DEFLATED, 31)
cdata = compobj.compress(data)
cdata += compobj.flush(zlib.Z_FINISH)
return cdata
def _gzip_decompress(data):
"""
Decompress data with gzip headers/trailers (wbits=31).
Single-shot approach.
:param data: GZIP-compressed bytes
:return: Decompressed bytes
"""
# If you need multi-member support, you'd need a streaming loop here.
return zlib.decompress(data, 31)
def _gzip_decompress_multimember(data):
"""
Decompress possibly multi-member GZIP data, returning all uncompressed bytes.
- We loop over each GZIP member.
- zlib.decompressobj(wbits=31) stops after the first member it encounters.
- We use 'unused_data' to detect leftover data and continue until no more.
"""
result = b""
current_data = data
while current_data:
# Create a new decompress object for the next member
dobj = zlib.decompressobj(31)
try:
part = dobj.decompress(current_data)
except zlib.error as e:
# If there's a decompression error, break or raise
raise ValueError("Decompression error: {}".format(str(e)))
result += part
result += dobj.flush()
if dobj.unused_data:
# 'unused_data' holds the bytes after the end of this gzip member
# So we move on to the next member
current_data = dobj.unused_data
else:
# No leftover => we reached the end of the data
break
return result
class GzipFile(object):
"""
A file-like wrapper that uses zlib at wbits=31 to mimic gzip compress/decompress,
with multi-member support. Works on older Python versions (including Py2),
where gzip.compress / gzip.decompress might be unavailable.
- In read mode: loads entire file, checks GZIP magic if needed, and
decompresses all members in a loop.
- In write mode: buffers uncompressed data, then writes compressed bytes on close.
- 'level' sets compression level (1..9).
- Supports text ('t') vs binary modes.
"""
# GZIP magic (first 2 bytes)
GZIP_MAGIC = b'\x1f\x8b'
def __init__(self, file_path=None, fileobj=None, mode='rb',
level=9, encoding=None, errors=None, newline=None):
"""
:param file_path: Path to file on disk (optional)
:param fileobj: An existing file-like object (optional)
:param mode: e.g. 'rb', 'wb', 'rt', 'wt', etc.