Skip to content

Commit

Permalink
Merge pull request #8 from gorouflex/main
Browse files Browse the repository at this point in the history
reflactor
  • Loading branch information
gorouflex authored Feb 23, 2024
2 parents 7c7d050 + 6620564 commit 0c330d4
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 67 deletions.
15 changes: 9 additions & 6 deletions UXTU4Mac/Assets/OCSnapshot/OCSnapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def get_min_max_from_match(self, match_text):
if match_text != "":
try:
min_list = match_text.split(".")
max_list = [x for x in min_list]
max_list = list(min_list)
min_list += ["0"] * (3-len(min_list)) # pad it out with 0s for min
min_list = [x if len(x) else "0" for x in min_list] # Ensure all blanks are 0s too
max_list += ["99"] * (3-len(max_list)) # pad it with 99s for max
Expand All @@ -54,17 +54,20 @@ def check_path_length(self, item):
# Get the last path component of the Path or BundlePath values for the name
name = os.path.basename(item.get("Path",item.get("BundlePath","Unknown Name")))
# Check the keys containing "path"
for key in item:
if "path" in key.lower() and isinstance(item[key],(str,unicode)) and len(item[key])>self.safe_path_length:
paths_too_long.append(key) # Too long - keep a reference of the key
paths_too_long.extend(
key
for key in item
if "path" in key.lower()
and isinstance(item[key], (str, unicode))
and len(item[key]) > self.safe_path_length
)
elif isinstance(item,(str,unicode)):
name = os.path.basename(item) # Retain the last path component as the name
# Checking the item itself
if len(item)>self.safe_path_length:
paths_too_long.append(item)
else: return paths_too_long # Empty list
if not paths_too_long: return [] # Return an empty array to allow .extend()
return [(item,name,paths_too_long)] # Return a list containing a tuple of the original item, and which paths are too long
return [] if not paths_too_long else [(item,name,paths_too_long)]

def snapshot(self, in_file = None, out_file = None, oc_folder = None, clean = False, oc_schema = None, force_update_schema = False):
oc_folder = self.u.check_path(oc_folder)
Expand Down
2 changes: 1 addition & 1 deletion UXTU4Mac/Assets/OCSnapshot/Scripts/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from os.path import dirname, basename, isfile
import glob
modules = glob.glob(dirname(__file__)+"/*.py")
modules = glob.glob(f"{dirname(__file__)}/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
55 changes: 18 additions & 37 deletions UXTU4Mac/Assets/OCSnapshot/Scripts/plist.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@
### ###

def wrap_data(value):
if not _check_py3(): return plistlib.Data(value)
return value
return plistlib.Data(value) if not _check_py3() else value

def extract_data(value):
if not _check_py3() and isinstance(value,plistlib.Data): return value.data
Expand Down Expand Up @@ -68,7 +67,7 @@ def writePlist(value, pathOrFile):

def load(fp, fmt=None, use_builtin_types=None, dict_type=dict):
if _check_py3():
use_builtin_types = True if use_builtin_types == None else use_builtin_types
use_builtin_types = True if use_builtin_types is None else use_builtin_types
# We need to monkey patch this to allow for hex integers - code taken/modified from
# https://github.com/python/cpython/blob/3.8/Lib/plistlib.py
if fmt is None:
Expand Down Expand Up @@ -154,7 +153,7 @@ def end_string():
parser.ParseFile(fp)
return p.root
else:
use_builtin_types = False if use_builtin_types == None else use_builtin_types
use_builtin_types = False if use_builtin_types is None else use_builtin_types
try:
p = _BinaryPlistParser(use_builtin_types=use_builtin_types, dict_type=dict_type)
except:
Expand Down Expand Up @@ -208,12 +207,11 @@ def writeDict(d):
def dumps(value, fmt=FMT_XML, skipkeys=False, sort_keys=True):
if _check_py3():
return plistlib.dumps(value, fmt=fmt, skipkeys=skipkeys, sort_keys=sort_keys).decode("utf-8")
else:
# We avoid using writePlistToString() as that uses
# cStringIO and fails when Unicode strings are detected
f = StringIO()
dump(value, f, fmt=fmt, skipkeys=skipkeys, sort_keys=sort_keys)
return f.getvalue()
# We avoid using writePlistToString() as that uses
# cStringIO and fails when Unicode strings are detected
f = StringIO()
dump(value, f, fmt=fmt, skipkeys=skipkeys, sort_keys=sort_keys)
return f.getvalue()

### ###
# Binary Plist Stuff For Py2 #
Expand Down Expand Up @@ -271,7 +269,7 @@ def _get_size(self, tokenL):
if tokenL == 0xF:
m = ord(self._fp.read(1)[0]) & 0x3
s = 1 << m
f = '>' + _BINARY_FORMAT[s]
f = f'>{_BINARY_FORMAT[s]}'
return struct.unpack(f, self._fp.read(s))[0]

return tokenL
Expand All @@ -280,11 +278,10 @@ def _read_ints(self, n, size):
data = self._fp.read(size * n)
if size in _BINARY_FORMAT:
return struct.unpack('>' + _BINARY_FORMAT[size] * n, data)
else:
if not size or len(data) != size * n:
raise InvalidFileException()
return tuple(int.from_bytes(data[i: i + size], 'big')
for i in range(0, size * n, size))
if not size or len(data) != size * n:
raise InvalidFileException()
return tuple(int.from_bytes(data[i: i + size], 'big')
for i in range(0, size * n, size))

def _read_refs(self, n):
return self._read_ints(n, self._ref_size)
Expand Down Expand Up @@ -312,18 +309,15 @@ def _read_object(self, ref):
elif token == 9: # \x09 or 0x09
result = True

# The referenced source code also mentions URL (0x0c, 0x0d) and
# UUID (0x0e), but neither can be generated using the Cocoa libraries.

elif token == 15: # \x0f or 0x0f
result = b''

elif tokenH == 0x10: # int
result = 0
for k in range((2 << tokenL) - 1):
for _ in range((2 << tokenL) - 1):
result = (result << 8) + ord(self._fp.read(1))
# result = int.from_bytes(self._fp.read(1 << tokenL),
# 'big', signed=tokenL >= 3)
# result = int.from_bytes(self._fp.read(1 << tokenL),
# 'big', signed=tokenL >= 3)

elif token == 0x22: # real
result = struct.unpack('>f', self._fp.read(4))[0]
Expand Down Expand Up @@ -354,22 +348,13 @@ def _read_object(self, ref):
s = self._get_size(tokenL)
result = self._fp.read(s * 2).decode('utf-16be')

# tokenH == 0x80 is documented as 'UID' and appears to be used for
# keyed-archiving, not in plists.

elif tokenH == 0xA0: # array
s = self._get_size(tokenL)
obj_refs = self._read_refs(s)
result = []
self._objects[ref] = result
result.extend(self._read_object(x) for x in obj_refs)

# tokenH == 0xB0 is documented as 'ordset', but is not actually
# implemented in the Apple reference code.

# tokenH == 0xC0 is documented as 'set', but sets cannot be used in
# plists.

elif tokenH == 0xD0: # dict
s = self._get_size(tokenL)
key_refs = self._read_refs(s)
Expand Down Expand Up @@ -576,7 +561,7 @@ def _write_object(self, value):
t = value.encode('utf-16be')
self._write_size(0x60, len(t) // 2)
self._fp.write(t)

elif isinstance(value, (bytes, bytearray)):
self._write_size(0x40, len(value))
self._fp.write(value)
Expand All @@ -590,11 +575,7 @@ def _write_object(self, value):
elif isinstance(value, dict):
keyRefs, valRefs = [], []

if self._sort_keys:
rootItems = sorted(value.items())
else:
rootItems = value.items()

rootItems = sorted(value.items()) if self._sort_keys else value.items()
for k, v in rootItems:
if not isinstance(k, basestring):
if self._skipkeys:
Expand Down
37 changes: 14 additions & 23 deletions UXTU4Mac/Assets/OCSnapshot/Scripts/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,20 +83,20 @@ def compare_versions(self, vers1, vers2, **kwargs):

def pad_length(self, var1, var2, pad = "0"):
# Pads the vars on the left side to make them equal length
pad = "0" if len(str(pad)) < 1 else str(pad)[0]
if not type(var1) == type(var2):
pad = "0" if not str(pad) else str(pad)[0]
if type(var1) != type(var2):
# Type mismatch! Just return what we got
return (var1, var2)
if len(var1) < len(var2):
if type(var1) is list:
var1.extend([str(pad) for x in range(len(var2) - len(var1))])
var1.extend([str(pad) for _ in range(len(var2) - len(var1))])
else:
var1 = "{}{}".format((pad*(len(var2)-len(var1))), var1)
var1 = f"{pad * (len(var2) - len(var1))}{var1}"
elif len(var2) < len(var1):
if type(var2) is list:
var2.extend([str(pad) for x in range(len(var1) - len(var2))])
var2.extend([str(pad) for _ in range(len(var1) - len(var2))])
else:
var2 = "{}{}".format((pad*(len(var1)-len(var2))), var2)
var2 = f"{pad * (len(var1) - len(var2))}{var2}"
return (var1, var2)

def check_path(self, path):
Expand Down Expand Up @@ -138,12 +138,8 @@ def grab(self, prompt, **kwargs):
# returning the result
timeout = kwargs.get("timeout", 0)
default = kwargs.get("default", None)
# If we don't have a timeout - then skip the timed sections
if timeout <= 0:
if sys.version_info >= (3, 0):
return input(prompt)
else:
return str(raw_input(prompt))
return input(prompt) if sys.version_info >= (3, 0) else str(raw_input(prompt))
# Write our prompt
sys.stdout.write(prompt)
sys.stdout.flush()
Expand All @@ -164,18 +160,13 @@ def grab(self, prompt, **kwargs):
if i:
i = sys.stdin.readline().strip()
print('') # needed to move to next line
if len(i) > 0:
return i
else:
return default
return i if len(i) > 0 else default

def cls(self):
os.system('cls' if os.name=='nt' else 'clear')

def cprint(self, message, **kwargs):
strip_colors = kwargs.get("strip_colors", False)
if os.name == "nt":
strip_colors = True
strip_colors = True if os.name == "nt" else kwargs.get("strip_colors", False)
reset = u"\u001b[0m"
# Requires sys import
for c in self.colors:
Expand Down Expand Up @@ -216,24 +207,24 @@ def head(self, text = None, width = 55):

# Header drawing method
def head(self, text = None, width = 55):
if text == None:
if text is None:
text = self.name
self.cls()
print(" {}".format("#"*width))
print(f' {"#" * width}')
mid_len = int(round(width/2-len(text)/2)-2)
middle = " #{}{}{}#".format(" "*mid_len, text, " "*((width - mid_len - len(text))-2))
middle = f' #{" " * mid_len}{text}{" " * (width - mid_len - len(text) - 2)}#'
if len(middle) > width+1:
# Get the difference
di = len(middle) - width
# Add the padding for the ...#
di += 3
# Trim the string
middle = middle[:-di] + "...#"
middle = f"{middle[:-di]}...#"
print(middle)
print("#"*width)

def resize(self, width, height):
print('\033[8;{};{}t'.format(height, width))
print(f'\033[8;{height};{width}t')

def custom_quit(self):
self.head()
Expand Down

0 comments on commit 0c330d4

Please sign in to comment.